簡體   English   中英

使用 JavaScript 原型對象時事件方法中的“this”關鍵字

[英]"this" keyword in event methods when using JavaScript prototype object

我正在嘗試在事件處理程序中訪問 JavaScript 中原型類的成員變量——在事件處理程序的情況下,我通常使用“this”關鍵字(或“that”[this的副本]) . 不用說,我遇到了一些麻煩。

以這個 HTML 片段為例:

<a id="myLink" href="#">My Link</a>

這個 JavaScript 代碼:

function MyClass()
{
  this.field = "value"
  this.link = document.getElementById("myLink");
  this.link.onclick = this.EventMethod;
}

MyClass.prototype.NormalMethod = function()
{
  alert(this.field);
}

MyClass.prototype.EventMethod = function(e)
{
  alert(this.field);
}

實例化 MyClass 對象並調用 NormalMethod 的工作方式與我期望的完全一樣(警告說“值”),但單擊鏈接會導致未定義的值,因為“this”關鍵字現在引用了事件目標(anchor () HTML 元素) .

我是 JavaScript 原型風格的新手,但在過去,使用閉包,我只是在構造函數中復制了“this”:

var that = this;

然后我可以通過“那個”對象訪問事件方法中的成員變量。 這似乎不適用於原型代碼。 有沒有另一種方法來實現這一目標?

謝謝。

你需要:

this.link.onclick = this.EventMethod.bind(this);

...'bind' 是 Prototype 的一部分,並返回一個函數,該函數使用正確設置的 'this' 調用您的方法。

你的"that=this"閉包成語仍然適用:

function MyClass()
{
    ...

    var that = this;
    this.link.onclick = function() {
        return that.EventMethod.apply(that, arguments);

        // that.EventMethod() works too here, however
        // the above ensures that the function closure
        // operates exactly as EventMethod itself does.

    };
}

你應該試試

this.link.onclick = this.EventMethod.bind(this);

如上所述,使用作為 Prototype 庫一部分的 bind 是解決這個問題的一種干凈的方法。 這個問題是另一個 SO 問題的副本,這里通過實現綁定方法而不包括整個原型庫來回答這個問題:

https://stackoverflow.com/a/2025839/1180286

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM