What is the difference between an object and a prototype in prototypal programming?

后端 未结 2 1238
南笙
南笙 2021-02-02 11:39

I\'m trying to understand the \"JavaScript way\" of creating and using objects and I think I\'m running into a misunderstanding of an object and a prototype.

In a new pr

2条回答
  •  北海茫月
    2021-02-02 11:51

    The prototype is just another object to which an object has an implicit reference.

    When you do:

    var obj = Object.create( some_object );
    

    ...you're saying that you want obj to try to fetch properties from some_object, when they don't exist on obj.

    As such, your second example would be closer to the way you'd use it. Every object that is created using Object.create(Dog) will have in its prototype chain, that Dog object. So if you make a change to Dog, the change will be reflected across all the objects that have Dog in the chain.

    If the main object has the same property as exists on the prototype object, that property is shadowing that property of the prototype. An example of that would be the null values you set on properties of Dog.

    If you do:

    var lab = Object.create(Dog);
    lab.color = 'golden';
    

    ...you're now shadowing the color property on Dog, so you'll no longer get null. You're not changing Dog in any way, so if I create another object:

    var colorless_dog = Object.create(Dog);
    

    ...this one will still get the null value from the prototype chain when accessing the color property.

    colorless_dog.color;  // null
    

    ...until you shadow it:

    colorless_dog.color = 'blue';
    colorless_dog.color;  // 'blue'
    

    So given your example:

    var lab = Object.create(Dog);
    lab.color = 'golden';
    lab.sheds = true;
    

    ...it looks something like this:

                  // labrador              // Dog
    lab.color---> color:'golden'           color:null
    lab.sheds---> sheds:true               sheds:null
    
    lab.fetch()--------------------------> fetch: function() {
                                              alert( this.color ); // 'golden'
                                              // "this" is a reference to the
                                              //    "lab" object, instead of "Dog"
                                           }
    

提交回复
热议问题