1

For example:

var Queue = function() {
    this.items = [];
};

Queue.prototype.enqueue = function(obj) {
    this.items.push(obj);
};

var queue = Object.create(Queue.prototype);
queue.enqueue('src');

Returns:

Uncaught TypeError: Cannot read property 'push' of undefined(…)

Whereas,

var queue = new Queue();
queue.enqueue('src');

works exactly the way I want it to. Is there a key ingredient in calling Object.create() that I am missing in my variable instantiation? Or does the Object.create() method require another pattern for assigning an array to be passed to its prototype objects?

Can someone please explain this minor detail to me because it behooves me to understand why it seems to work in other examples I find online except for my own.. Much appreciated!

Friendly-Robot
  • 1,124
  • 14
  • 24

3 Answers3

3

Object.create does create an empty object and does not call the constructor method to initialise it.

You want to use the new operator. That's what it was made for.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Because in the first case your object created doesn't have items array

Oxi
  • 2,918
  • 17
  • 28
1

You're creating your object via Object.create() and referencing the prototype of that constructor. The constructor function itself will never be called when you do that. Object.create() is not magic; you pass it an object, and that's the object it uses. You're passing the prototype object from your constructor, which is a perfectly nice object, but there's nothing that will cause the constructor function itself to be invoked.

Pointy
  • 405,095
  • 59
  • 585
  • 614