将单击事件绑定到类内的方法

3
在我的对象构造函数中,我创建了一些标签,并且需要将它们引用到同一个对象的方法中。
以下是我的代码示例:
$(document).ready(function(){
    var slider = new myObject("name");
});

function myObject(data){
    this.name = data;

    //Add a span tag, and the onclick must refer to the object's method
    $("body").append("<span>Test</span>");
    $("span").click(function(){
        myMethod(); //I want to exec the method of the current object
    }); 


    this.myMethod = myMethod;
    function myMethod(){
        alert(this.name); //This show undefined
    }

}

使用这段代码调用方法,但它并不是对象的引用(this.name显示未定义)。我该如何解决?
非常感谢!

2
这是因为this指的是当前作用域(也就是触发它的事件,比如点击)。 - Gokul Kav
1个回答

6
一种简单的方法是:
function myObject(data){
    this.name = data;

    // Store a reference to your object
    var that = this;

    $("body").append("<span>Test</span>");
    $("span").click(function(){
        that.myMethod(); // Execute in the context of your object
    }); 

    this.myMethod = function(){
        alert(this.name); 
    }
}

另一种方法是使用$.proxy

function myObject(data){
    this.name = data;

    $("body").append("<span>Test</span>");
    $("span").click($.proxy(this.myMethod, this)); 

    this.myMethod = function(){
        alert(this.name); 
    }
}

或者我们可以直接使用 data 而不是 this.name - Gokul Kav
@GokulKav 或者 $.proxy,就像我刚刚添加的一样。或者使用 bind。有多种解决方案。 - bfavaretto
@GokulKav 谢谢。为什么不使用 data 添加一个答案呢?展示不同选项的多个答案很好。 - bfavaretto
我在我的课堂上尝试了这个,它没有绑定到点击事件,只是在文档加载时执行该方法。 - Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接