JavaScript 原型“这个”问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13996794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:25:49  来源:igfitidea点击:

JavaScript prototype 'this' issue

javascript

提问by FlyingCat

This is a follow up question from my last question.

这是我上一个问题的后续问题。

Simple javascript prototype issue

简单的javascript原型问题

I am a bit new using JavaScript prototypeso sorry for the second post.

我对 JavaScript 有点陌生,prototype所以很抱歉第二篇文章。

I want to assign the clicked element idto the this.namearray.

我想点击的元素分配idthis.name数组。

task.prototype.init=function(){  
      this.name=[];  //this.name array has to be defined here

        for (var i; i<5; i++){
            var Link=document.createElement('a');
                Link.innerHTML='click';
                Link.id=value[i];   //I want to assign the value to the this.name array
                Link.href='#'
                Link.onclick=this.changeName;
                document.body.appendChild(Link);
         }
}
task.prototype.changeName=function(){  

     //How do I push the this.id to the property this.name?

     //the code below won't work because this refer to the <a> element. 
     this.name.push(this.id);     

    return false;
    }

Any tips for the task?

任务有什么提示吗?

回答by bfavaretto

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

你的原型没问题,问题是this事件处理程序总是导致事件被触发的元素。在 JavaScript 中,this函数内部的值取决于函数的调用方式

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

如果要this绑定到某个值,可以使用以下命令创建绑定函数Function.prototype.bind

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

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

但请注意,这bind仅适用于 IE9+。一种解决方法是:

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

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

(样式说明:我会使用link而不是Link; js 中的约定是将大写首字母留给构造函数)。

回答by JohnnyHK

Use bindto set the desired thisfor the changeNamecallback:

使用bind设置所需thischangeName回调:

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