1

我有一个具有两个属性的基本 javascript 类。我想在点击事件中记录一个的值。这是我得到的:

function Clicker(/*string*/var1, /*id*/var2) {
    this.name = var1;
    this.clickerid = var2;
    this.clickevent = function() {
        console.log("1: " + this.name);
        console.log("2: " + this);
        console.log("3: " + window.testClicker.name);
    };

    var element = document.getElementById(this.clickerid);
    element.addEventListener("click", this.clickevent, false);
}

window.onload = function() {
    window.testClicker = new Clicker("lorem ipsum", "checkbox1");
};

<input id="checkbox1" type="checkbox" value="1" checked>

当我运行测试时,我在日志中看到以下内容:

1: undefined
2: <input id=​"checkbox1" type=​"checkbox" value=​"1" checked>​
3: lorem ipsum

我期待看到第一行和第三行匹配。建议?

4

3 回答 3

3

The value of this depends on the context in which a function is called.

When the event listener fires, the function is called in the context of the element the event is associated with - not the object the function was copied from.

Use bind to override the context (it generates a new function that calls the original function in whatever context you define).

element.addEventListener("click", this.clickevent.bind(this), false);

This is equivalent to:

element.addEventListener(
    "click", 
    function (context) {
        return function () {
            context.clickevent();
        };
    }(this),
    false
);
于 2013-09-16T20:46:04.310 回答
2

我认为这可能是一个上下文问题,以下工作是否可行:

function Clicker(/*string*/var1, /*id*/var2) {
    this.name = var1;
    this.clickerid = var2;
    var self = this;
    this.clickevent = function() {
        console.log("1: " + self.name);
        console.log("2: " + this);
        console.log("3: " + window.testClicker.name);
    };

    var element = document.getElementById(this.clickerid);
    element.addEventListener("click", this.clickevent, false);
}

正如您在 2nd 中看到的那样console.logthis指的是复选框,而不是Cliker对象

于 2013-09-16T20:44:08.587 回答
0

为了完整起见,有三种可能的解决方案:

  1. 使用dm03514 的回答中建议的封闭变量。
  2. 按照昆汀的回答bind中的建议使用。
  3. 使用事件侦听器接口 /如在处理包含由事件侦听器调用的 'this' 关键字的对象方法中的范围内handleEvent所建议的那样。
于 2013-09-16T20:48:14.583 回答