Fra*_*ser 5 javascript scope square-bracket module-pattern
我一直在使用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");
Run Code Online (Sandbox Code Playgroud)
从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
}
};
Run Code Online (Sandbox Code Playgroud)