【发布时间】:2017-10-26 20:12:13
【问题描述】:
我尝试改变一些将方法调用到命名空间的方式。
- 调用父方法(我认为不可能)
- 创建和调用继承函数
- 在另一个方法中调用(主要是 jquery onReady 事件函数)(this.MyFunction() 不起作用)
我在文件中拆分每个命名空间(希望保持这种方式)
我尝试How to call function A from function B within the same namespace?,但没有成功拆分命名空间。
我的小提琴样本只有 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");我不认为我可以改变这一点。我尝试使用它的方式,它更像是一个继承功能。但我不知道有没有办法做到这一点?
也许我应该更改我的命名空间方法?也许原型会做我想做的事?
【问题讨论】:
标签: javascript jquery namespaces