2016-05-29 60 views
1

我有可以简化这样的类:这是怎么来的,_这是否引用了一个对象的不同实例?

Captcha = function(el) { 
    this.el = $(el); 
    _this = this; 

    captchas.push(this); 
}; 


Captcha.prototype.render = function(grecaptcha){ 
    console.log(this.el.dom[0]); 
    console.log(_this.el.dom[0]) 
}; 

类与传入作为EL两个不同的DOM元素intantiated两次。

渲染在全局回调函数运行时运行。

captchas = []; 

//We need this for captchas. 
window.CaptchaCallback = function(){ 
    app.captchas.forEach(function(capt){ 
    capt.grecaptcha = grecaptcha; 
    capt.render(); 
    }); 
}; 

出于某种原因,this.el.dom[0]引用了两种不同的元素,但_this.el.dom[0]总是引用类,为什么最后一个实例?

+1

你想做什么?你打算让'_this'变量起作用吗? – Pointy

回答

2

你离开了var您在初始化_this:因此

var Captcha = function(el) { 
    this.el = $(el); 
    var _this = this; // don't forget var! 

    captchas.push(this); 
}; 

你的代码是创建一个全局变量,而不是本地的。

当然,它是本地的构造函数,所以它不会在外面看到。你可以做_this构建对象的属性:

this._this = this; 

,但不会使有很大的意义,因为你需要this找到_this反正。

+0

然后调用'render'会抛出 – Oriol

+0

是的,这就是答案最后部分的意图。 – Pointy

1

因为您没有用var关键字声明_this,所以隐式声明了全局变量。构造函数的代码则等同于:

var _this; 
Captcha = function(el) { 
    this.el = $(el); 
    _this = this; 

    captchas.push(this); 
}; 

因为它是全球性的,_this始终保持创建的最后一个实例的值。

相关问题