Note that there are some explanatory texts on larger screens.

plurals
  1. POPrototypical inheritance - writing up
    primarykey
    data
    text
    <p>So I have these 2 examples, from javascript.info:</p> <p>Example 1:</p> <pre><code>var animal = { eat: function() { alert( "I'm full" ) this.full = true } } var rabbit = { jump: function() { /* something */ } } rabbit.__proto__ = animal rabbit.eat() </code></pre> <p>Example 2:</p> <pre><code>function Hamster() { } Hamster.prototype = { food: [], found: function(something) { this.food.push(something) } } // Create two speedy and lazy hamsters, then feed the first one speedy = new Hamster() lazy = new Hamster() speedy.found("apple") speedy.found("orange") alert(speedy.food.length) // 2 alert(lazy.food.length) // 2 (!??) </code></pre> <p>Start from Example 2: when the code reaches <code>speedy.found</code>, it finds no <code>found</code> property in <code>speedy</code>, and so it climbs up to the prototype and changes it there. That's why <code>food.length</code> is equal for both hamsters, in other words they have the same stomach.<br><br> From this I understand, that when writing up and adding a new property which doesn't exist, the interpreter will go up the prototype chain until it finds the property, and THEN change it.</p> <p>BUT in Example 1 something else happens:<br> we run <code>rabbit.eat</code>, which changes <code>rabbit.full</code>. <code>full</code> property is nowhere to be found, so it should go up the prototype chain to (to object??), and well, I'm not sure what happens here. In this example the property <code>full</code> of <code>rabbit</code> is created and changed, while in the first example it goes up the prototype chain because it cannot find the property.</p> <p>I'm confused and cannot see why this happens.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload