我有一个可以像这样简化的类:
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])
};
类被实例化两次,两个不同的 DOM 元素作为 el 传入。
渲染在全局回调函数运行时运行。
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]
总是引用了最后一个实例上课,为什么?
最佳答案
当你初始化 _this
时,你离开了 var
:
var Captcha = function(el) {
this.el = $(el);
var _this = this; // don't forget var!
captchas.push(this);
};
因此,您的代码创建了一个全局变量,而不是本地变量。
当然,它是该构造函数的局部变量,因此无论如何它都不会在外部可见。您可以使 _this
成为构造对象的属性:
this._this = this;
但这没有多大意义,因为无论如何您都需要 this
才能找到 _this
。
关于javascript - 为什么 this 和 _this 引用了一个对象的不同实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37511159/