0

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?

2
  • 2
    Where did you get this Rabbit.prototype = Animal; part from? It should be Rabbit.prototype = Object.create(Animal.prototype) Commented May 13, 2020 at 7:58
  • I just played with code and tried this assignment. Also, I debugged this in chrome and first, Rabbit called, then Animal function and it had already assigned 'name' as 'Animal', but 'undefined' if I didn't set the prototype for Rabbit. That was the confusing point I asked. Commented May 13, 2020 at 8:35

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.