Prototypical inheritance - writing up [duplicate]

13    1 year ago

So I have these 2 examples, from

Example 1:

var animal = {
  eat: function() {
    alert( "I'm full" )
    this.full = true

var rabbit = {
  jump: function() { /* something */ }

rabbit.__proto__ = animal 

Example 2:

function Hamster() {  }
Hamster.prototype = {
  food: [],
  found: function(something) {

// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()


alert( // 2
alert( // 2 (!??)

Start from Example 2: when the code reaches speedy.found, it finds no found property in speedy, and so it climbs up to the prototype and changes it there. That's why food.length is equal for both hamsters, in other words they have the same stomach.

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.

BUT in Example 1 something else happens:
we run, which changes rabbit.fullfull 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 full of rabbit is created and changed, while in the first example it goes up the prototype chain because it cannot find the property.

I'm confused and cannot see why this happens.

Answers { 0 }