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 show undefined) どうすれば解決できますか?

どうもありがとう!

4

1 に答える 1

6

それを達成するための1つの簡単な方法:

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); 
    }
}
于 2013-06-24T22:13:13.753 に答える