这个!=这是用javascript实现的(嗯,有时…)
例1这个!=这是用javascript实现的(嗯,有时…),javascript,jquery,Javascript,Jquery,例1 var Reptile = function () { var reptile = this; this.showBla = function() { alert(reptile.bla); } } var turtle = new Reptile(); turtle.bla = 'whatever'; turtle.showBla(); 例2 var Reptile = function () { this.showBla = function()
var Reptile = function () {
var reptile = this;
this.showBla = function() {
alert(reptile.bla);
}
}
var turtle = new Reptile();
turtle.bla = 'whatever';
turtle.showBla();
例2
var Reptile = function () {
this.showBla = function() {
alert(this.bla);
}
}
var turtle = new Reptile();
turtle.bla = 'whatever';
turtle.showBla();
例1合法吗?因为有时它似乎把事情搞糟了,直接在构造函数中定义“this” 是的,它是合法的,并且在您可能需要在函数中定义一个函数的情况下非常有用,该函数可以通过“this”指向其他对象的方式调用。书籍建议将此变量命名为var=this 示例1是维护对当前实例的引用的常见模式。在回调情况下,例如:
setTimeout(turtle.showBla, 0);
示例1的var爬行动物…
保存了此
引用,并将显示'whatever'
。示例2将显示未定义的,除非您在调用端手动分配范围(例如,在jQuery中):
看起来很好。您不需要在构造函数中定义任何内容,只需存储一个引用。没问题。你不能自己定义这个。因为这两个例子都是防弹合法的,你能提供一些有时会把事情搞糟的代码吗?
setTimeout($.proxy(turtle.showBla, turtle), 0);