【问题标题】:JS prototype inheritance confusingJS原型继承令人困惑
【发布时间】:2020-05-13 07:51:14
【问题描述】:

实际代码。

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);

我希望有控制台输出: 兔子 50

但我有 动物 50

谁能解释为什么 Animal 函数不重写它的 name 属性?

【问题讨论】:

  • 你从哪里得到这个Rabbit.prototype = Animal; 部分?应该是Rabbit.prototype = Object.create(Animal.prototype)
  • 我刚刚玩过代码并尝试了这个作业。另外,我在 chrome 中调试了它,首先调用了 Rabbit,然后调用了 Animal 函数,如果我没有为 Rabbit 设置原型,它已经将“名称”分配为“动物”,但“未定义”。这就是我问的令人困惑的地方。

标签: javascript inheritance


【解决方案1】:

Animal 只是一个函数

'function'对象有一个属性'name'

例如

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


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

所以Animal对象有一个属性'name',函数对象也有一个属性'name'

你可以试试这个

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);

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);

【讨论】:

    【解决方案2】:

    使用Object.create,你应该得到类似的结果:

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      相关资源
      最近更新 更多