[英]Javascript prototype: how do I call a method within another method?
[英]In javascript how can I call one prototype method in another prototype method?
假设我有一个功能:
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
引用绑定在每个函数调用上,包括调用回调函数,例如您在“.draggable()”设置中使用的函数。 当被调用时, this
将在“method02”函数中设置为与this
不同的内容。
是的,你可以像在这个问题的其他答案中那样在词法范围内手动缓存this
。 但是,我建议的替代方法是使用$.proxy
或function.bind
作为$.proxy
创建绑定方法。
绑定方法往往被称之为具有稳定this
。 我发现它们更具可读性,而不是在更高范围内this
进行奇怪的命名
怎么样?
test.prototype.method02=function(){
this.method01.apply(this);
// do some other stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.