javascript 在javascript中如何在另一种原型方法中调用一个原型方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9749969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:42:40  来源:igfitidea点击:

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

javascriptcallprototype

提问by hh54188

suppose I have a function:

假设我有一个功能:

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'
}

Edited: in fact the method01 like this:

编辑:实际上method01是这样的:

test.prototype.method02=function(){
    $('.cpy').resizable({

    }).draggable({
        start:function(e,ui){
            this.method01();
        }
    });
}

回答by Pointy

test.prototype.method02=function(){
    var testThing = this;
    $('.cpy').resizable({

    }).draggable({
        start:function(e,ui){
            testThing.method01();
        }
    });
}

You have to preserve the thisreference in another local variable so that the callback function can use it when calling the other method. The thisreference is bound upon each and every function call, including calls to callback functions like the one you're using in the ".draggable()" setup. When that's called thiswill be set to something different from the thisin your "method02" function.

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

回答by J. Holmes

Yea, you could manually cache thisin the lexical scope like other answers in this question suggest. However, the alternative that i would suggest is to create a bound method using $.proxyor function.bindas your call back.

是的,您可以this像这个问题中的其他答案所建议的那样,在词法范围内手动缓存。但是,我建议的替代方法是使用$.proxyfunction.bind作为您的回调创建绑定方法。

Bound methods are always called with a stable this. I find them to be much more readable, than bizarrely named references to thisin higher scopes

绑定方法总是使用 stable 调用this。我发现它们比this在更高范围内的奇怪命名的引用更具可读性

回答by L. Monty

whats about

怎么了

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