JavaScript prototype 'this' issue

前端 未结 2 1524
耶瑟儿~
耶瑟儿~ 2020-12-10 15:53

This is a follow up question from my last question.

Simple javascript prototype issue

I am a bit new using JavaScript prototype so sorry for the

2条回答
  •  独厮守ぢ
    2020-12-10 16:31

    Your prototype is okay, the problem is that this on event handlers is always the element that caused the event to be triggered. In JavaScript, the value of this inside a function depends on how the function is called.

    If you want this to be bound to a certain value, you can create a bound function with Function.prototype.bind:

    var newChangeName = this.changeName.bind(this);
    Link.onclick = newChangeName;
    

    Note however that bind is IE9+ only. A workaround would be:

    var that = this;
    Link.onclick = function() {
        that.changeName();
    };
    

    (Style note: I'd use link instead of Link; the convention in js is to leave uppercase initials to constructors).

提交回复
热议问题