在我的对象构造函数中,我创建了一些标签,并且需要将它们引用到同一个对象的方法中。
以下是我的代码示例:
使用这段代码调用方法,但它并不是对象的引用(this.name显示未定义)。我该如何解决?
非常感谢!
以下是我的代码示例:
$(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显示未定义)。我该如何解决?
非常感谢!
this
指的是当前作用域(也就是触发它的事件,比如点击)。 - Gokul Kav