Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript继承澄清_Javascript_Inheritance - Fatal编程技术网

javascript继承澄清

javascript继承澄清,javascript,inheritance,Javascript,Inheritance,我如何让最后一行开始工作 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 =

我如何让最后一行开始工作

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*
您需要将狗的原型设置为新动物。
Dog.prototype=新动物();
Object.create创建一个新的空对象,并使用参数has prototype创建此对象

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

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

在这里,您可以在新的狗上下文中调用动物构造函数。

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

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;

可以找到构造函数、继承和原型的介绍。

可能的重复代码中没有与动物的继承您完全没有做任何事情来链接您的狗和动物功能。你认为这怎么行?你试过什么?@meagar我想这是他的问题。。。如何链接它们?;)我是否需要设置Dog.prototype.constructor=Dog@KingKongFrog:对于您的用例,您不需要;然而,这样做可能是一个好主意,以防其他代码检查该属性以进行类型标识。实际上,我从来没有看到过这样做的重要原因。这就是我的主要困惑所在。为什么/什么时候我必须设置原型。构造函数?@KingKongFrog:这是一个完全不同的(而且完全有效的)问题。这也不是一个好主意,使用父对象具有原型的指令。父级必须是不带参数的可构造的。构造函数可能会对原型声明执行无用的操作。在这个特定的示例中,构造函数中的继承有点无用。在这个特定的示例中,它实际上非常有用。它演示了在创建特定于实例的成员时如何将其初始化为instanceOfDog.name
this.name=name
在狗身上不再需要,因为动物已经这样做了。如果你有一大堆需要验证和设置的值,那么在Dog,Cat,Bird中有一行。。。我会处理好的。
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;