简体   繁体   中英

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

    .....
    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 :

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

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"

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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