내 객체의 생성자에서 일부 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
를 사용하여 : 그것을 달성하기
의 this'는 트리거 이벤트가 될 것이다 (현재 범위를 참조 할 것'때문에 즉, 클릭) –