在javascript中,我如何在另一个原型方法中调用一个原型

In javascript how can I call one prototype method in another prototype method?

本文关键字:原型 一个 调用 另一个 javascript 方法      更新时间:2023-09-26

假设我有一个函数:

function test(){}
test.prototype.method01=function(){
    //do something
}
test.prototype.method02=function(){
    //how can I call the method01?
    //this.method01()...?
    //but the chrome through an error:
    //Uncaught TypeError: Object #<HTMLImageElement> has no method 'method01'
}

编辑时间:事实上,方法01是这样的:

test.prototype.method02=function(){
    $('.cpy').resizable({
    }).draggable({
        start:function(e,ui){
            this.method01();
        }
    });
}
test.prototype.method02=function(){
    var testThing = this;
    $('.cpy').resizable({
    }).draggable({
        start:function(e,ui){
            testThing.method01();
        }
    });
}

您必须在另一个局部变量中保留this引用,以便回调函数在调用其他方法时可以使用它。this引用绑定在每个函数调用上,包括对回调函数的调用,如您在".draggabe()"设置中使用的回调函数。当它被调用时,this将被设置为与"method02"函数中的this不同的值。

是的,您可以像本问题中的其他答案一样,在词法范围中手动缓存this。然而,我建议的另一种选择是使用$.proxyfunction.bind作为回调创建一个绑定方法。

绑定方法总是使用稳定的this调用。我发现它们比在更高范围

中对this的奇怪命名引用更可读

的特点

test.prototype.method02=function(){
     this.method01.apply(this);
     // do some other stuff
}