简体   繁体   中英

JS prototype inheritance confusing

Actual code.

 function Animal(name) { this.name = name; } function Rabbit(speed) { Animal.call(this, 'Rabbit'); this.speed = speed; } Rabbit.prototype = Animal; var rabbit = new Rabbit(50); console.log(rabbit.name, rabbit.speed);

I expected to have console output: Rabbit 50

But I have Animal 50

Can anybody explain why Animal function doesn't rewrite its name property?

Animal just a function

'function' object has a property 'name'

for example

function app(){
 console.log("hello")
}
console.log(app.name) // "app"


function Animal(name){
 this.name = name;
}
console.log(Animal.name) // "Animal"

so Animal object has a property 'name', function object also has a property 'name'

you can try this

function Animal(name) {
  this.notname = name; //do not use "name" as a property name
}

function Rabbit(speed) {
  Animal.call(this, 'Rabbit');
  this.speed = speed;
}

Rabbit.prototype = Animal;
var rabbit = new Rabbit(50);
console.log(rabbit.notname, rabbit.speed);

or

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

function Rabbit(speed) {
  Animal.call(this, 'Rabbit');
  this.speed = speed;
}

Rabbit.prototype = new Animal(); 
//you should point the Rabbit.prototype to a Animal object,not a function

var rabbit = new Rabbit(50);
console.log(rabbit.name, rabbit.speed);

Using Object.create , you should end up with something like:

 function Animal(name) { this.name = name } function Rabbit(speed) { Animal.call(this, 'Rabbit') this.speed = speed } Rabbit.prototype = Object.create(Animal.prototype) // If you don't set this line, `new Rabbit` would call `Animal` constructor Rabbit.prototype.constructor = Rabbit var rabbit = new Rabbit(50) console.log(rabbit.name, rabbit.speed)

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