Gra*_*hao 13 javascript namespaces
现在我有一个遵循长链名称空间的模块,例如:
TOP.middle.realModuleName = function () { /*...*/ }
Run Code Online (Sandbox Code Playgroud)
我需要在页面上使用此模块,我不确定此页面是否包含名称空间Top.middle.所以我必须做以下事情:
if (typeof TOP !== 'undefined' && TOP.middle && TOP.middle.realdModuleName) {
new TOP.middle.realModuleName();
}
Run Code Online (Sandbox Code Playgroud)
我认为这个if陈述看起来很长很冗长.任何人都有关于如何为这种情况编写更好的参数检查模式的建议?
试试这个简单的辅助函数:
function exists(namespace) {
var tokens = namespace.split('.');
return tokens.reduce(function(prev, curr) {
return (typeof prev == "undefined") ? prev : prev[curr];
}, window);
}
Run Code Online (Sandbox Code Playgroud)
它接受一个String输入,并返回该对象(如果存在).你可以像这样使用它:
var module = exists("TOP.middle.realModuleName");
Run Code Online (Sandbox Code Playgroud)
例如:
exists("noexist"); // returns undefined
exists("window"); // returns DOMWindow
exists("window.innerHeight"); // returns Number
exists("window.innerHeight.toString"); // returns Function
exists("window.innerHeight.noexist"); // returns undefined
Run Code Online (Sandbox Code Playgroud)
它也适用于评估为false的表达式:
testNum = 0;
testBool = false;
testNull = null;
exists("testNum"); // returns 0
exists("testBool"); // returns false
exists("testNull"); // returns null
Run Code Online (Sandbox Code Playgroud)
只是将它封装在TRY/CATCH中?
try {
return new TOP.middle.blablabla();
}
catch(err) {
// oh no!
}
return null;
Run Code Online (Sandbox Code Playgroud)