JavaScript原型"this"问题 [英] JavaScript prototype 'this' issue

查看:72
本文介绍了JavaScript原型"this"问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我上一个问题的跟进问题.

This is a follow up question from my last question.

简单的javascript原型问题

我对使用JavaScript prototype 有点陌生,因此对第二篇文章表示歉意.

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

我想将单击的元素 id 分配给 this.name 数组.

I want to assign the clicked element id to the this.name array.

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

该任务有什么提示吗?

推荐答案

您的原型还可以,问题是事件处理程序上的 this 始终是导致事件被触发的元素.在JavaScript中,其中 this 的值函数取决于函数的调用方式.

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 绑定到某个值,则可以使用

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;

但是请注意, bind 仅是IE9 +.解决方法是:

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

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

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

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

这篇关于JavaScript原型"this"问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆