0

Let's say I have the following code:

(function($) {
    var Obj = {
        init: function() {
            var c1 = Object.create(this.MyChild);
            var c2 = Object.create(this.MyChild);
            c1.init(); //not working!!!
        },
        MyChild: function() {
            this.init = function() {
                console.log('calling MyChild init function');   
            }
        }
    };

    Obj.init();
})(jQuery);

When creating Obj, I used object literal as I don't need to create the instance of it, and when creating MyChild objects, I used the constructor function and used Object.create as I need to create multiple instances of MyChild.

However, when I call Object.create, it doesn't work, when c1.init() is called, it says the init function is undefined, but if I replaced Object.create(this.MyChild) to:

var c1 = new this.MyChild(); 
c1.init();

why?

Josh
  • 692
  • 2
  • 9
  • 38
  • 1
    `Object.create` is *not* a replacement for `new`! What's wrong with calling the constructor? – Bergi Jan 15 '14 at 19:28
  • @Bergi I thought they are pretty much the same, it's just I have read some articles saying that "Object.create" should be used when creating the instance, instead of using "new". I think I'll just stick with var c1 = new this.MyChild(); – Josh Jan 15 '14 at 20:09
  • Screw those articles. You can use `Object.create` when you don't need initialisation, and you should use it when you must not use initialisation. Maybe have a look at http://stackoverflow.com/a/11253826/1048572, http://stackoverflow.com/a/14267886/1048572 or http://stackoverflow.com/q/10898786/1048572 – Bergi Jan 15 '14 at 20:16

2 Answers2

1

I think you should use

var c1 = Object.create(this.MyChild.prototype);

instead of

var c1 = Object.create(this.MyChild);
S. A.
  • 3,714
  • 2
  • 20
  • 31
1

Object.create(func) doesn't do the same thing as new func()!

Object.create() creates an (otherwise empty!) object, which prototype will be set to the object, that is passed to that function (MDN)

To use Object.create() in your example, you could modify it like this:

(function($) {
    var Obj = {
        init: function() {
            var c1 = Object.create(this.MyChild);
            var c2 = Object.create(this.MyChild);
            c1.init(); //not working!!!
        },
        MyChild: {
            init: function() {
                console.log('calling MyChild init function');   
            }
        }
    };

    Obj.init();
})(jQuery);

But in this case everything will just POINT to your MyChild object. Properties of MyChild will be shared among every object, that you create using Object.create().

basilikum
  • 10,378
  • 5
  • 45
  • 58