gpt4 book ai didi

Javascript的原型(prototype),如何继承类?

转载 作者:行者123 更新时间:2023-11-28 07:06:01 25 4
gpt4 key购买 nike

我需要 Javascript 中两个类之间的继承关系。我喜欢在构造函数中声明属性;对于方法,原型(prototype):

function Animal(){
this.someProperty = 'someProperty';
this.init();
}
Animal.prototype = {
init : function(){ }
anotherMethod : function(){ }
}

我认为声明这样的方法比以下方法更具可读性:

 Animal.prototype.init = function(){ }
Animal.prototype.anotherMethod = function(){}

但是当我需要从另一个类继承某个类时,我找不到按照我的方式实现的方法。这不起作用:

  Cat.prototype = new Animal();
Cat.prototype = {
init : function(){ }
}

我知道我可以这样做:

  Cat.prototype = new Animal();
Cat.prototype.init = function(){ }
Cat.prototype.anotherMethod = function(){ }

但是,有办法按照我的方式做吗?

最佳答案

查看一些继承方法以使继承发挥作用:

第一个链接中的示例可能会总结它,它相似但略有不同:

function Mammal(name){ 
this.name=name;
this.offspring=[];
}
Mammal.prototype.haveABaby=function(){
var newBaby=new Mammal("Baby "+this.name);
this.offspring.push(newBaby);
return newBaby;
}
Mammal.prototype.toString=function(){
return '[Mammal "'+this.name+'"]';
}


Cat.prototype = new Mammal(); // Here's where the inheritance occurs
Cat.prototype.constructor=Cat; // Otherwise instances of Cat would have a constructor of Mammal
function Cat(name){
this.name=name;
}
Cat.prototype.toString=function(){
return '[Cat "'+this.name+'"]';
}


var someAnimal = new Mammal('Mr. Biggles');
var myPet = new Cat('Felix');
alert('someAnimal is '+someAnimal); // results in 'someAnimal is [Mammal "Mr. Biggles"]'
alert('myPet is '+myPet); // results in 'myPet is [Cat "Felix"]'

myPet.haveABaby(); // calls a method inherited from Mammal
alert(myPet.offspring.length); // shows that the cat has one baby now
alert(myPet.offspring[0]);

有一些框架专注于原型(prototype)继承,可以为您管理一些管道。

关于Javascript的原型(prototype),如何继承类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31710696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com