OOP。从方法内部调用方法 [英] OOP. Calling methods from within methods
问题描述
如何从类中的函数调用类方法?我的代码是:
How do I call class methods from functions within the class? My code is:
var myExtension = {
init: function() {
// Call onPageLoad
},
onPageLoad: function() {
// Do something
},
}
我试过......
onPageLoad();
...来自init方法,但它说它没有定义。
... from within the init method but it's saying it's not defined.
我对谷歌没有太多运气,因为我不懂所用的语法。我在网上找到的所有JS OOP示例都采用不同的格式。我正在使用Mozilla用于扩展开发的格式。
I'm not having much luck with google because I don't understand the syntax used. All the JS OOP examples I find online are in a different format. I'm using the format Mozilla use for extension development.
推荐答案
假设您已调用 init
像这样:
myExtension.init();
那么它应该是:
init: function() {
// before
this.onPageLoad();
// after
}
但是在Javascript函数中实际上并没有绑定到对象,您可以在任何其他对象上调用任何函数,如下所示:
But in Javascript functions are not actually bound to objects and you can call any function on any other object, like this:
myExtension.init.call(anotherObject); // or
myExtension.init.apply(anotherObject);
在此示例中此
在<$ c内$ c> init 将是 anotherObject
,它没有定义 onPageLoad
。如果你想支持这种用法,你必须手动引用初始对象:
In this example this
within init
would be anotherObject
, which doesn't have onPageLoad
defined. If you want to support this kind of usage you'll have to manually reference the initial object:
init: function() {
// before
myExtension.onPageLoad();
// after
}
这篇关于OOP。从方法内部调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!