javascript - 为什么 this 和 _this 引用了一个对象的不同实例?

标签 javascript

我有一个可以像这样简化的类:

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/

相关文章:

javascript - 如何缩短 typescript 中的界面名称?

javascript - jquery中的淡入淡出效果

javascript - 从另一个 URL 创建图像提要

javascript - 从数组中随机选择项目,并且仅在之前未使用过的情况下使用

javascript - 火狐。 InvalidStateError : An attempt was made to use an object that is not, 或不再可用

javascript - 使用 history.js 使用多个 GET 参数

php - 如何从 ajax 调用获取图表数据到 javascript

javascript - 为什么我不能将参数传递给 addEventListener 中的匿名函数,如何解决?

javascript - 适当的内联 try catch

javascript - 数组/HTML 中的函数