Construct/start object via string parameter in a function

Asked

Viewed 79 times

0

I need to start objects dynamically with Javascript

Ex:

Example class:

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

Function to dynamically load and instantiate classes:

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

Final code (for implementation):

var variavelqualquer = iniciaClasse('sayhello');

The problem:

This is returning me a mistake, and I understand more or less why, once I pass a string in the parameter nomeDaClasse, since I don’t have the class builder being instantiated right away.

The function iniciaClasse() is a module Loader, and will load, start and return the class I inform, therefore, when I call such a function, the constructor (sayhello) doesn’t exist yet.

So...

If I do: iniciaClasse(sayHello) - I get a mistake because sayHello() does not yet exist

If I do: iniciaClasse('sayHello') - I get an error because the parameter passed is a string (I think that’s why)

Is there any way to fix it?

  • tries to use Singleton project pattern.

  • Have any answers solved what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

2 answers

2


Actually the way the code is and use iniciaClasse(sayHello) no mistake, if given is doing something else.

To do what you want you need to take the function identifier in the window dictionary to be able to 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 in the Github for future reference.

This solves what is in the question but makes the code useful. There is another problem.

  • You are giving the following error: (index):76 Uncaught Typeerror: funcao is not a constructor at startClasse ((index):76) at window.onload ((index):79) see Jsfiddle: https://jsfiddle.net/oqvsxk9L/

  • @Allanandrade do not know why it started happening that at the time it worked, this is one of the problems of JS, it breaks compatibility.

0

as it is done, you would have to take 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 to try to modularize your script. A good thing would be to use the RequireJS, even if you don’t do it asynchronously. If it’s something very simple 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();

doing so, you can even put the define in archives js separate and then make a bundle and minify of these files, and your script will continue to work as expected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.