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
JavaScript prototype 'this' issue
提问by FlyingCat
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 second post.
我对 JavaScript 有点陌生,prototype
所以很抱歉第二篇文章。
I want to assign the clicked element id
to the this.name
array.
我想点击的元素分配id
给this.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 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.
你的原型没问题,问题是this
事件处理程序总是导致事件被触发的元素。在 JavaScript 中,this
函数内部的值取决于函数的调用方式。
If you want this
to 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 bind
is IE9+ only. A workaround would be:
但请注意,这bind
仅适用于 IE9+。一种解决方法是:
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).
(样式说明:我会使用link
而不是Link
; js 中的约定是将大写首字母留给构造函数)。