从 IIFE 动态调用构造函数
Dynamically calling constructor from IIFE
考虑以下因素:
function windowTest() { }
(function () {
function test() { }
var test1 = new test(); // Works fine.
var test2 = new window["windowTest"](); // Works since windowsTest is declared globally.
var test3 = new window["test"](); // Fails since in an IIFE.
// How can I create a testObj if I only have the string "test"?
})();
基本上,我想创建一个对象,其函数在 IIFE 中声明。
原因
var test3 = new window["test"]();
失败是因为 test
没有全局声明。如果您想访问直接在 IIFE 中声明的项目,如您所知,您可以通过名称访问它们。
new test();
另一种方法是将函数存储在某种对象中,然后像使用 window
一样访问该对象。这几乎总是解决这类问题的方法。
(function() {
var context = {
test: function() {
console.log('new test');
}
};
var test = new context['test']();
})();
最后一种方式使用 eval
. eval
is almost always a really bad idea. 真的,应该避免这种方式,除非您只是为了兴趣而滥用语言。但是你可以在这种情况下使用它。
(function() {
function test() {
console.log('new test');
}
var test = eval('new test()');
})();
您可以将函数绑定到此:
function(){
//your code using
this.test("Hi");
this["test"]("Hi");
}.call({
//function declarations:
test:window.alert,
});
仍然是一个 IIFE,所以它不能在全局上下文中工作:
this.test("Hi");//reference Error
考虑以下因素:
function windowTest() { }
(function () {
function test() { }
var test1 = new test(); // Works fine.
var test2 = new window["windowTest"](); // Works since windowsTest is declared globally.
var test3 = new window["test"](); // Fails since in an IIFE.
// How can I create a testObj if I only have the string "test"?
})();
基本上,我想创建一个对象,其函数在 IIFE 中声明。
原因
var test3 = new window["test"]();
失败是因为 test
没有全局声明。如果您想访问直接在 IIFE 中声明的项目,如您所知,您可以通过名称访问它们。
new test();
另一种方法是将函数存储在某种对象中,然后像使用 window
一样访问该对象。这几乎总是解决这类问题的方法。
(function() {
var context = {
test: function() {
console.log('new test');
}
};
var test = new context['test']();
})();
最后一种方式使用 eval
. eval
is almost always a really bad idea. 真的,应该避免这种方式,除非您只是为了兴趣而滥用语言。但是你可以在这种情况下使用它。
(function() {
function test() {
console.log('new test');
}
var test = eval('new test()');
})();
您可以将函数绑定到此:
function(){
//your code using
this.test("Hi");
this["test"]("Hi");
}.call({
//function declarations:
test:window.alert,
});
仍然是一个 IIFE,所以它不能在全局上下文中工作:
this.test("Hi");//reference Error