我一直在使用 JavaScript 中的模块模式,并且对范围和方括号表示法 (SBN) 有疑问。
请考虑以下简单示例。
(function (module) {
function myMethod(text) {
console.log(text);
}
module.init = function (name) {
// here I want to do something like
// eval(name)("hello");
// using SBN, e.g.
..[name].call(this, "hello");
};
})(window.Module = window.Module || {});
Module.init("myMethod");
从内部init
函数是否可以调用myMethod
使用SBN?
您可以将所有方法放入一个对象中。
function myMethod(text) {
console.log(text);
}
var methods = {myMethod: myMethod, ... };
module.init = function (name) {
// here I want to do something like
// eval(name)("hello");
// using square bracket notation.
if(methods.hasOwnProperty(name)){
methods[name].call(this, "hello");
}
else {
// some error that the method does not exist
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)