0
function Objecte(name){

    this.name=name;

}

Objecte.prototype.look=function(){

    return function(){

        alert(this.name);

    };

}

オブジェクトの属性にアクセスしようとしていますが、関数を呼び出すと未定義と警告されます。

extintor = new Objecte("extintor");

$(document).on('dblclick',"#extintor",extintor.look());
4

3 に答える 3

1

thisは字句的に定義されていません。返された関数がそれを使用できるようにするには、その値を取得する必要があります。

Objecte.prototype.look=function(){
    var self = this;
    return function() {
        alert(self.name);
    };
}

使用することもできます$.proxy

Objecte.prototype.look=function(){
    return $.proxy(function() {
        alert(this.name);
    }, this);
}

または.bind()最新のブラウザで

Objecte.prototype.look=function(){
    return function() {
        alert(this.name);
    }.bind(this);
}
于 2013-05-13T17:52:16.697 に答える