0

I have a scenario, where I need to create objects dynamically.

In my example, an object meta contains the name for the constructor function to be used during initialization Object.create().

At the moment using the following code, I am able to create the objects dynamically but the property name is not defined.

I need that property on the result;

What is wrong in my script? Do you know a better way to achieve the same result?

      (function () {
            var costructors = {
                A: function () {
                    this.name = 'A';
                    console.log(this.name);
                },
                B: function () {
                    this.name = 'B';
                    console.log(this.name);
                },
                C: function () {
                    this.name = 'C';
                    console.log(this.name);
                }
            },
            meta = {
                A: true,
                B: true,
                C: true,
            },
            result = [];
            function createObjs() {
                Object.keys(meta).forEach(function (type) {
                    var obj = Object.create(costructors[type].prototype);
                    result.push(obj);
                }.bind(this));
            }
            createObjs.call(this);
            console.log(result);
        })();

1
  • Why the .bind(this) on the anonymous function of .forEach()? Commented Jul 17, 2015 at 13:08

3 Answers 3

1

You haven't defined a prototype for any of the constructors, so you're not creating the name in your instances, since you're creating an object from their prototype, not from their constructor. Try

Object.create(constructors[type])
Sign up to request clarification or add additional context in comments.

Comments

1

An alternative without using Object.create would be:

var obj = new costructors[type]();

instead of:

var obj = Object.create(costructors[type].prototype);

Comments

0

Actually, Object.create does not call the constructor function, but only creates a new object from the given prototype. Any member variables can be provided via a property object:

var obj = Object.create(
  constructors[type].prototype,
  { 'name' : { value: 'A', writable: true}}
);

Comments

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.