Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从IIFE动态调用构造函数_Javascript_Iife - Fatal编程技术网

Javascript 从IIFE动态调用构造函数

Javascript 从IIFE动态调用构造函数,javascript,iife,Javascript,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"]();

考虑以下几点:

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();
另一种方法是将函数存储在某种对象中,然后像使用
窗口那样访问该对象。这几乎总是解决这类问题的办法

(函数(){
变量上下文={
测试:函数(){
console.log(“新测试”);
}
};
var-test=新上下文['test']();
})();原因

var test3 = new window["test"]();
失败是因为未全局声明
test
。如您所知,如果您想访问直接在IIFE中声明的项,您可以按名称访问它们

new test();
另一种方法是将函数存储在某种对象中,然后像使用
窗口那样访问该对象。这几乎总是解决这类问题的办法

(函数(){
变量上下文={
测试:函数(){
console.log(“新测试”);
}
};
var-test=新上下文['test']();

})();您可以将函数绑定到此:

function(){
 //your code using
 this.test("Hi");
 this["test"]("Hi");
}.call({
 //function declarations:
 test:window.alert,
});
仍然是一种生活,因此在全球范围内它不会起作用:

this.test("Hi");//reference Error

您可以将函数绑定到此:

function(){
 //your code using
 this.test("Hi");
 this["test"]("Hi");
}.call({
 //function declarations:
 test:window.alert,
});
仍然是一种生活,因此在全球范围内它不会起作用:

this.test("Hi");//reference Error

Re
test3
:为什么您需要访问
窗口
对象上的函数,而不是直接使用它?为什么new test()不起作用?test()确实起作用,更新了注释。@MikeC,我只是想找一种语法,可以让“var test3=new window[“test”()”起作用。有点像是如何使用“反射”来调用全局声明的对象。但是我想在IIFE中做这件事。
测试
的范围是IIFE——因为它不在
窗口
,不,没有办法让它工作。你可以使用
eval
,但是很恶心。您试图解决的实际问题是什么?re
test3
:为什么您需要在
window
对象上访问该函数,而不是直接使用它?为什么new test()不起作用?test()确实起作用,更新了注释。@MikeC,我只是在寻找一种语法,使“var test3=new window[“test”()”起作用。有点像是如何使用“反射”来调用全局声明的对象。但是我想在IIFE中做这件事。
测试
的范围是IIFE——因为它不在
窗口
,不,没有办法让它工作。你可以使用
eval
,但是很恶心。你想解决的实际问题是什么?