我是第一次研究 javascript 继承,但我似乎无法让它工作,或者也许我没有正确理解它。 所以我这里有一些代码,让我们看一下:
<script language="javascript" type="text/javascript">
//object and prototype
function cat(name){//object constructor
this.name = name;//property
this.talk = function(){//method
console.log(this.name + " say meeow");
}
}
cat1 = new cat("Cat 1 Felix")
cat1.talk();
cat2 = new cat("cat 2 Joy")
cat2.talk()
//inheritance
function isleManCat(name){
cat.call(this,name)
this.feature = "no tail"
this.detail = function(){
console.log(this.name + " has " + this.feature);
}
}
isleManCat.prototype = new cat();
cat3 = new isleManCat("isle of Man cat")
cat3.talk();
cat3.detail();
</script>
所以我这里有 2 个 cats 对象,cat1 和 cat2 打印预期结果:
Cat 1 Felix say meeow
cat 2 Joy say meeow
。那么cat3是一个isleOfMan()猫,它应该继承自cat(),我本以为它会继承cat()的name属性,但它打印出未定义:
undefined say meeow
undefined has no tail
有人可以告诉我为什么它不起作用以及我做错了什么吗,因为我似乎不明白? 谢谢
最佳答案
派生 cat
的第三只小猫不会产生预期结果,因为 cat
构造函数不会被 isleManCat
的构造函数调用自动神奇地!而你的第三只小猫根本没有名字!
// You need to pass the name of the whole cat to this constructor
// to later give it as argument to base constructor (i.e. cat())
function isleManCat(name){
// This is calling cat constructor function setting the "this"
// keyword to the "this" of isleManCat
cat.call(this, name);
this.feature = "no tail"
this.detail = function(){
console.log(this.name + " has " + this.feature);
}
}
在 ECMA-Script 5.x 中,您还可以使用 Function.prototype.apply
和 arguments
保留关键字将 isleOfMan
构造函数的参数传递为cat
的数组:
function isleManCat(){
cat.apply(this, arguments);
this.feature = "no tail"
this.detail = function(){
console.log(this.name + " has " + this.feature);
}
}
而且,在 ECMA-Script 2015 及更高版本中,您可以使用剩余参数:
function isleManCat(...args){
// This is calling cat constructor function setting the "this"
// keyword to the "this" of isleManCat
cat.apply(this, args);
this.feature = "no tail"
this.detail = function(){
console.log(this.name + " has " + this.feature);
}
}
关于javascript - 如何实现javascript继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503969/