Build / start object via string parameter in a function

0

I need to dynamically start objects with JavaScript

Ex:

Sample class:

function sayhello() {
    this.init = function() {
        alert('Hello');
    }
}

Function to load and instantiate classes dynamically:

function iniciaClasse(nomeDaClasse) {
    return new nomeDaClasse();
}

Final (execution) code:

var variavelqualquer = iniciaClasse('sayhello');

The problem:

This is returning me an error, and I understand more or less why, since I pass a string in the parameter nomeDaClasse , since I do not have the class constructor to be instantiated from immediate.

The function iniciaClasse() is a loader module, and will load, start and return the class I am reporting, so when I call that function, the constructor ( sayhello ) does not yet exists.

Being so ...

If I do: iniciaClasse(sayHello) - I get an error because sayHello() does not exist yet

Is there any way to fix this?

    
asked by anonymous 29.07.2017 / 14:40

2 answers

2

Actually the way the code is and use iniciaClasse(sayHello) does not give any error, if it is it is doing something else.

To do what you want you need to get the function identifier in the window dictionary so you can call it, like this:

function sayhello() {
    this.init = function() {
        console.log('Hello');
    }
}

function iniciaClasse(nomeDaClasse) {
    var funcao = window[nomeDaClasse];
    return new funcao();
}

var variavelqualquer = iniciaClasse('sayhello');

I put it in GitHub for future reference.

This solves what's in the question, but does make the code useful. That's another problem.

    
29.07.2017 / 15:08
0

As it is done, you would have to get the function that instantiates the direct object in the window, this can be problematic, especially if this function is redeclared elsewhere in the script.

In this case, I advise you to use it to try to modularize your script . It would be good to use RequireJS , even if you do not do it asynchronously. If it is something simple that you want to build, you can use the following script.

(function () {
  var libs = [];
  
  Object.defineProperty(window, "define", {
    configurable: false,
    writable: false,
    value: function (name, callback) {
      libs[name] = callback();
    }
  });
  
  Object.defineProperty(window, "require", {
    configurable: false,
    writable: false,
    value: function (name) {
      return libs[name];
    }
  });
})();

define("world", function () {
  var World = function () {};  
  World.prototype.sayHello = function () {
    console.log("Hello World!");
  }  
  return World;
});

var MyClass = require("world");
var myObject = new MyClass();
myObject.sayHello();

In this way, you can even put define into js separated files and then bundle and minify of these files, and your script will continue to function as expected. >     

02.08.2017 / 17:16