“this” keyword in event methods when using JavaScript prototype object

故事扮演 提交于 2019-11-26 03:25:45

问题


I\'m trying to access the member variables of a prototype class in JavaScript in an event handler -- something I\'d typically use the \"this\" keyword for (or \"that\" [copy of this] in the case of event handlers). Needless to say, I\'m running into some trouble.

Take, for example, this HTML snippet:

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

And this JavaScript code:

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);
}

Instantiating a MyClass object and calling NormalMethod works exactly like I expect it to (alert saying \"value\"), but clicking the link results in an undefined value because the \"this\" keyword now references the event target (the anchor () HTML element).

I\'m new to the prototype JavaScript style, but in the past, with closures, I\'ve simply made a copy of \"this\" in the constructor:

var that = this;

And then I could access members variables in event methods via the \"that\" object. That doesn\'t seem to work with prototype code. Is there another way to achieve this?

Thanks.


回答1:


Your "that=this" closure idiom is still applicable:

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.

    };
}



回答2:


You need:

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

...'bind' is part of Prototype, and returns a function which calls your method with 'this' set correctly.




回答3:


You should try

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



回答4:


As stated above, using bind which is a part of the Prototype library is a clean way to solve this problem. This question is a duplicate of another SO question which is answered here with implementation of the bind method without including the whole prototype library :

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



来源:https://stackoverflow.com/questions/1369004/this-keyword-in-event-methods-when-using-javascript-prototype-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!