Why doesn't the initialized JavaScript object contain a prototype object?

I tried using the following code to add a method start

to an object:

var Bounce = Bounce || {
    Info : {},
    Game : {}
};

Bounce.Game.prototype.start = function() {
    Bounce.log("Starting " + new Bounce.Info());
}

      

But this results in the following error (on line Bounce.Game.prototype.start

):

Uncaught TypeError: Cannot set property "start" to undefined

Looking at the subject in the Chrome console, I see that it does not contain the object prototype

(but it has toString

, valueOf

and constructor

etc.).

This can be easily fixed by adding the following line before accessing the prototype:

Bounce.Game = function() {};

      

I don't know why this is necessary when the object is already initialized?

W3Schools tells me, "Every JavaScript object has a prototype," but that doesn't seem to be the case.

+3


source to share


2 answers


Conceptually, all objects have a prototype, but only function objects (including type constructors Object

, Array

although they do not produce the function) have the propertywith the name prototype

, They don't match.

If you're reading the ECMAScript spec, the prototype is usually represented as [[Prototype]] , which is an implementation detail in a JS engine, not a language function. However, in some versions of the engine, [[Prototype]] is opened and can be accessed using a property __proto__

(non-standard).




By the way:

  • If you want to access [[Prototype]] , this Object.getPrototypeOf()

    is your friend.

  • When used, a instanceof b

    it actually compares the a

    [[Prototype]] string to a b

    prototype

    property .

  • And why do we say what null

    is the prototype of everything? This also does not apply to prototype

    , but [[Prototype]] :

    Object.getPrototypeOf(Object.getPrototypeOf({})) // null
    Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf([]))) // null
    Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(new String("")))) // null
    
    // or shorter like this
    ({}).__proto__.__proto__ // null
    ([]).__proto__.__proto__.__proto__ // null
    ("").__proto__.__proto__.__proto__ // null
    
          

+4


source


So, based on @ Leo's comments , I am thinking about this solution to use a simple object {}

with its prototype.

We have this object:

var Bounce = Bounce || {
    Info : {},
    Game : {}
};

      

Let's define a property prototype

for a given object



Object.defineProperty(Bounce.Game, 'prototype', {
    get: function() {
      return Object.getPrototypeOf(Bounce.Game); 
    }
});

      

We can now use the prototype as usual:

Bounce.Game.prototype.start = function(){
  console.log('start');
};

Bounce.Game.start();

      

Check it out: http://jsbin.com/bapuvo/3/edit

+2


source







All Articles