0

From JSON, I want to request the name of a constructor and have it execute in javascript.

json.js

{
    objArray = [
        {
            "funcName":"executeMe"
        }
     ]
}

page.js

var newInstance = createInstanceByName(objArray[0].funcName); //"executeMe"
//Functions like: var newInstance = new lib.executeMe();

lib.js (I have no control over) looks like this:

(lib.executeMe = function() {
    this.initialize(img.executeMe);
}).prototype = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,200,200);

I was hoping I could repurpose the solution from this thread but it's important that the variable newInstance is available to me throughout page.js - it's not enough to have me pass it the context. I need the assignment to happen here.

How could createInstanceByName() work?

Community
  • 1
  • 1
ベンノスケ
  • 619
  • 6
  • 7

1 Answers1

2
function createInstanceByName(funcName) {
    return new lib[funcName];
}

If you need to pass arguments, then put them in an Array, and do this instead:

function createInstanceByName(funcName, args) {
    var inst = Object.create(lib[funcName].prototype)
    lib[funcName].apply(inst, args);
    return inst;
}

You could also use the arguments object by slicing it instead of using an Array.

The Object.create method isn't available in old browsers, but it can be shimmed sufficiently enough for this purpose.

the system
  • 9,244
  • 40
  • 46