简体   繁体   English

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

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

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: 编辑:实际上方法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();
        }
    });
}

You have to preserve the this reference in another local variable so that the callback function can use it when calling the other method. 您必须在另一个局部变量中保留this引用,以便回调函数在调用另一个方法时可以使用它。 The this reference is bound upon each and every function call, including calls to callback functions like the one you're using in the ".draggable()" setup. this引用绑定在每个函数调用上,包括调用回调函数,例如您在“.draggable()”设置中使用的函数。 When that's called this will be set to something different from the this in your "method02" function. 当被调用时, this将在“method02”函数中设置为与this不同的内容。

Yea, you could manually cache this in the lexical scope like other answers in this question suggest. 是的,你可以像在这个问题的其他答案中那样在词法范围内手动缓存this However, the alternative that i would suggest is to create a bound method using $.proxy or function.bind as your call back. 但是,我建议的替代方法是使用$.proxyfunction.bind作为$.proxy创建绑定方法。

Bound methods are always called with a stable this . 绑定方法往往被称之为具有稳定this I find them to be much more readable, than bizarrely named references to this in higher scopes 我发现它们更具可读性,而不是在更高范围内this进行奇怪的命名

whats about 怎么样?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM