2016-05-29 62 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始終保持創建的最後一個實例的值。

相關問題