Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这个!=这是用javascript实现的(嗯,有时…)_Javascript_Jquery - Fatal编程技术网

这个!=这是用javascript实现的(嗯,有时…)

这个!=这是用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()

例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() {
       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);