简体   繁体   English

javascript根据类名称动态创建类实例

[英]javascript dynamically create class instance from a class name

I have many block of codes that look like this: 我有很多看起来像这样的代码块:

    .....
    var headerEl = document.createElement("div");
    headerEl.id = "headerDiv";
    document.body.appendChild(headerEl);
    var headerBlock = new Header(headerEl);

    var footerEl = document.createElement("div");
    footerEl.id = "footerDiv";
    document.body.appendChild(footerEl);
    var footerBlock = new Footer(footerEl);
    .....

Now I want to create a function "createBlock" that will do the above code, so I just have to pass in the params like this 现在,我想创建一个函数“ createBlock”来执行上面的代码,所以我只需要传递这样的参数

    .....
    var headerBlock = createBlock("headerDiv", Header);
    var footerBlock = createBlock("footerDiv", Footer);
    .....

I have tried this but it doesn't work 我已经尝试过了,但是没有用

function createBlock (divName, className){
    var myDiv = document.createElement("div")
    myDiv.id = divName;
    document.body.appendChild(myDiv);
    var block = new className(myDiv);
    return block;
}

Use the apply invocation pattern or Function.prototype.call : 使用apply调用模式或Function.prototype.call

function createBlock (divName, className){
    var myDiv = document.createElement("div")
    myDiv.id = divName;
    document.body.appendChild(myDiv);
    var block = className.call(null, myDiv);
    return block;
}

This will require both constructor functions, Header and Footer , to be scope-safe by checking for this 这将要求构造函数HeaderFooter通过检查this范围是否安全

function Header(arg) {
  if(this instanceof Header) {
    //initialise
    return this;
  }
  else {
    return new Header(arg);
  }
}
function createBlock (divName, className){
    var myDiv = document.createElement("div")
    myDiv.id = divName;
    document.body.appendChild(myDiv);
    var block = new window[className](myDiv);
    return block;
}

var headerBlock = createBlock("headerDiv", "Header");
var footerBlock = createBlock("footerDiv", "Footer");

Note the quotes around "Header" and "Footer" 请注意"Header""Footer"周围的引号

See Dynamically loading a typescript class (reflection for typescript) 请参阅动态加载打字稿类(打字稿的反映)

You need to use: 您需要使用:

var newInstance = Object.create(window[className].prototype);
newInstance.constructor.apply(newinstance, params);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM