简体   繁体   中英

How to use prototypal inheritance?

I have an object that looks like this:

var o = {
    prototype: {
        foo: function(){console.log('bar');}
    }
}

My understanding is that when I do Object.create(o) the returned object should have a method .foo .

However, what if I also attach a create method to o ?

var o = {
    prototype: {
        foo: function(){console.log('bar');}
    },
    create: function(){}
}

Does the prototypal magic of javascript do something different in this case?

Your understanding is incorrect. You would have to do something like this:

var o = {
    __proto__: {
        foo: function() {
            console.log('bar');
        }
    }
};

so that the object returned from Object.create(o) would have the foo method.

var o2 = Object.create(o);
o2.foo(); // prints bar

Modern browsers have implemented the __proto__ as a way of accessing the internal [[Prototype]] chain of an object. It is not actually in the standard and it's direct use is discouraged and may even lead to suboptimal code due to possible optimizations done by the browser on the __proto__ property.

In the example above the __proto__ fakes the internal representation of the prototype chain to demonstrate that Object.create connects the internal [[Prototype]] , ie the __proto__ property.

The .prototype property which is on all function objects, for example:

var o = function() {};
typeof o.prototype  // returns "object"

Is used by the new operator in order to populate the internal [[Prototype]] (ie the __proto__ property) and build that instances prototype chain.

If you did the following

var o = {
    __proto__: {
        foo: function() {
            console.log('bar');
        }
    }, 
    create: function() {},
};

o2 = Object.create(o);

o2 would have both methods except they would be on different levels of the prototype chain, something like:

{ 
  __proto__: {
     create: function() { ... },
     __proto__: {
        foo: function() { ... }
     }
}

Prototype is just a property that points on constructor function. In JS, you can add properties dynamically on any objects. If you want to add properties in a class (I mean all objects which is an instance of that class), you must add properties to its prototype.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM