问题
In the constructor of my object, I create some span tag and I need to refers them to a method of the same object.
Here is an example of my code:
$(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
}
}
With this code the method is called, but it is not a reference to the object (this.name show undefined) How can I resolve that?
Thanks a lot!
回答1:
One simple way to achieve that:
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);
}
}
Another way, using $.proxy:
function myObject(data){
this.name = data;
$("body").append("<span>Test</span>");
$("span").click($.proxy(this.myMethod, this));
this.myMethod = function(){
alert(this.name);
}
}
来源:https://stackoverflow.com/questions/17285968/bind-a-click-event-to-a-method-inside-a-class