我尝试改变一些方法来调用命名空间的方法。
- 调用父方法(我认为不可能)
- 创建并调用继承函数
- 在另一个方法中调用(主要是 jquery onReady 事件函数)(this.MyFunction() 不起作用)
我分割了文件中的每个 namespace (希望保持这种方式)
我尝试How to call function A from function B within the same namespace?但我没有成功分割命名空间。
我的 fiddle 样本只有 1 个子命名空间,但可能更多。
https://jsfiddle.net/forX/kv1w2rvc/
/**************************************************************************
// FILE Master.js
***************************************************************************/
if (!Master) var Master = {};
Master.Print= function(text){
console.log("master.Print :" + text);
$("body").append("<div>master.Print : " + text + "</div>");
}
/**************************************************************************
// FILE Master.Test1.js
***************************************************************************/
if (!Master) var Master = {};
if (!Master.Test1) Master.Test1 = {};
/**************************************************************************
* Descrition :
* Function for managing event load/documentReady
**************************************************************************/
Master.Test1.onReady = function () {
$(function () {
Master.Test1.Function1(); //try to replace because need all namespace.
try {
this.Function2(); //not working
}
catch(err) {
console.log("this.Function2 not working");
$("body").append("<div>this.Function2 not working</div>");
}
try {
this.Print("onReady"); //not working
}
catch(err) {
console.log("this.Print not working");
$("body").append("<div>this.Print not working</div>");
}
try {
Print("onReady"); //not working
}
catch(err) {
console.log("Print not working");
$("body").append("<div>Print not working</div>");
}
});
}
Master.Test1.Function1 = function () {
console.log("Function1");
$("body").append("<div>Function1</div>");
this.Function3(); //working because not inside another function
}
Master.Test1.Function2 = function () {
$("body").append("<div>Function2</div>");
console.log("Function2");
}
Master.Test1.Function3 = function () {
$("body").append("<div>Function3</div>");
console.log("Function3");
Master.Print("Function3"); //try to replace because need all namespace.
}
Master.Test1.onReady();
我使用 Master.Test1.Function1();我想更改它,因为 Function1 位于同一命名空间内。
我使用 Master.Print("Function3");我认为我无法改变这一点。我尝试使用它的方式,它更像是一个继承函数。但我不知道是否有办法做到这一点?
也许我应该更改我的命名空间方法?也许原型(prototype)会做我想要的事情?
最佳答案
您可以捕获 this
在变量中,因为 this
里面$(function() {})
将指向document
目的。如果您从未更改 onReady
的调用上下文,则以下内容将起作用-- 即它总是在 Test1
上被调用对象并且不在其他上下文中调用:
Master.Test1.onReady = function () {
var self = this;
$(function () {
self.Function1();
// ..
});
}
访问Print
您必须使用 Master
进行引用对象如:Master.Print()
因为它在 Test1
中不可用对象
关于javascript命名空间调用其他函数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44193005/