在我的对象的构造函数中,我创建了一些 span 标记,我需要将它们引用到同一对象的方法。
这是我的代码示例:
$(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 显示未定义) 我该如何解决?
非常感谢!
最佳答案
实现这一目标的一种简单方法:
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);
}
}
关于javascript - 将点击事件绑定(bind)到类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17285968/