【问题标题】:javascript inheritance clarificationjavascript继承说明
【发布时间】:2013-12-05 02:55:58
【问题描述】:

如何让最后一行工作?

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

Animal.prototype.speak = function(){
    alert('Hi, I\'m ' + this.name);
}

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

Dog.prototype.bark = function(){
  alert('Woof!');  
};

var fido = new Dog('Fido');
fido.bark(); // Woof!
fido.speak(); // Hi, I'm Fido *can't get this to work*

【问题讨论】:

  • 您的代码中没有 Animal 继承
  • 您完全没有做任何事情来链接您的 Dog 和 Animal 函数。你期望它如何工作?你试过什么?
  • @meagar 我认为这是他的问题......如何链接它们? ;)

标签: javascript inheritance


【解决方案1】:

您需要将 Dog 原型设置为新的 Animal。

Dog.prototype = new Animal();

【讨论】:

  • 是否需要设置 Dog.prototype.constructor = Dog;
  • @KingKongFrog:对于您的用例,您不需要;但是,如果其他代码检查该属性以进行类型识别,这样做可能是一个好主意。在实践中,我从未见过这样做的重要理由。
  • 这是我主要困惑的地方。为什么/什么时候必须设置prototype.constructor?
  • @KingKongFrog:这是一个完全不同(而且完全有效)的问题。
  • 使用具有原型的父对象的实例也不是一个好主意。父级必须是无参数可构造的。并且构造函数肯定会为原型声明做一些无用的操作。
【解决方案2】:
...
function Dog(name){
    this.name = name;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor= Dog;

Dog.prototype.bark = function(){
    alert('Woof!');  
};
...

Object.create 创建一个新的空对象并使用参数有这个对象的原型。

你也可以在构造函数中进行继承:

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

在这里,您在新的 Dog 上下文中调用 Animal 构造函数。

【讨论】:

  • 在这个具体的例子中,构造函数中的继承有点没用。
  • 在这个具体的例子中,它实际上非常有用。它演示了实例特定成员 name 在创建时如何初始化为 instanceOfDog.name。在 Dog 中不再需要 this.name=name,因为 Animal 已经这样做了。如果您有一大堆值需要验证和设置,那么 Dog、Cat、Bird 中的一行就可以解决这个问题。
【解决方案3】:

简而言之;你可以这样做:

var Dog = function(name){
  //re use Animal constructor
  Animal.call(this,name);
  //you can do Animal.apply(this,arguments); as well
};
//set up the prototype chain
Dog.prototype = Object.create(Animal.prototype);
//repair the constructor property
Dog.prototype.constructor = Dog;

关于构造函数、继承和原型的介绍可以看here

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多