javascript prototypal inheritance and the 'new' keyword

I've been playing around with prototypal inheritance in JavaScript and have been confused by the behavior of the new keyword. I cannot understand why the [[prototype]] property of the inheriting object points to Function.prototype and not the prototype of the inherited object. Consider 2 constructor functions (below):

function Animal(name) {
    this.name = name;
}

function Cat(name) {
    Animal.call(this, name);
}

Cat.prototype = new Animal();

Querying the prototype of the constructor function Cat , I get some interesting results:

Cat.__proto__ === Animal.prototype; //returns false -- shouldn't this be true?
Cat.__proto__ === Function.prototype; //returns true
Cat.prototype instanceof Animal; //returns true, as expected

My understanding was that the [[prototype]] of Cat should be updated to point to Animal.prototype when we set it's prototype property to a new instance of Animal , which should in essence

  • create a new object based on Animal.prototype and
  • internally set Cat.[[prototype]] to Animal 's external prototype property?
  • I've tried this in both Chrome and FF with the same result. What gives?

    Also, when we assign Cat.prototype to a new Animal() , what should Cat.prototype be? ie:

    //if Cat.prototype = new Animal();
    //then
    Cat.prototype === Animal.prototype; //get false. Should this be true?
    

    Cat.__proto__ === Animal.prototype; //returns false -- shouldn't this be true?
    Cat.__proto__ === Function.prototype; //returns true
    

    The Cat constructor is a function. Therefore, it inherits from Function.prototype which in turn inherits from Object.prototype . This is also true for the Animal constructor and all other function objects.

    Just because you assigned to Cat.prototype doesn't change the inheritance link of the Cat constructor itself (inheritance links are immutable anyway).

    Note that Cat instances don't inherit from Cat , but from Cat.prototype . So, you don't care about the prototype link of the Cat constructor anyway.


    That the [[prototype]] property is owned by Object instead of by Constructor function. So in your example,you will find that

    Cat.prototype.__proto__ === Animal.prototype; //Return true
    

    Common say

    Instance.__proto__ === Constructor.prototype; //Retrun true
    

    Cat is a Constructor function that is a instance of Function type,so you saw this result

    Cat.__proto__ === Function.prototype; //Return true 
    

    My english is so terriable,but I wish that I have explained something. :-)

    链接地址: http://www.djcxy.com/p/30058.html

    上一篇: VS. JavaScript中的原型

    下一篇: JavaScript原型继承和'new'关键字