0

I have a couple of modules that I want to instantiate the object from a string. This is usually easy when classes/objects etc are on the global scope window

new window["MyClass"]()

With require JS the modules aren't in the window scope and they're not on this if within a class.

Do you know what scope I require?

define(['testclassb'], function(TestClassB) {
  var TestClassA, testclassa;

  TestClassA = (function() {
    function TestClassA() {
      console.log("A");
      new this["TestClassB"](); #errors with undefined function
      new window["TestClassB"](); #errors with undefined function
      new TestClassB(); #works fine
    }

    TestClassA.prototype.wave = function() {
      return console.log("Wave");
    };

    return TestClassA;

  })();

  testclassa = new TestClassA();
  return testclassa.wave();
});

1 Answer 1

2

I have a couple of modules that I want to instantiate the object from a string

That's mostly a bad idea and indicates a code smell. Do you really need that?

Do you know what scope I require?

TestClassB is a local variable, which is impossible to access by name. Since you are already statically declaring testclassb as a dependency, there should be no reason not to use the static variable TestClassB as well.

However, require.js allows you to synchronously require() already loaded modules, so you could as well use

new (require("testclassb"))();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Yeh I'm not fond of it tbh, but the object to be instantiated is determined by data send over a socket. So I wanted to avoid a nasty ton of if logic, so I opted for a hash to map the strings to the objects pastie.org/7452137
Yes, that's what you always can do (and what is the right thing in this case) :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.