我第一次看到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只猫对象,cat1和cat2打印出预期结果:
Cat 1 Felix say meeow
cat 2 Joy say meeow
。然后cat3是一个isleOfMan()cat,它应该继承自cat(),我原以为它会从cat()继承name属性,但它会打印undefined:
undefined say meeow
undefined has no tail
有人可以让我知道为什么它不起作用以及我做错了,因为我似乎不明白这一点? 感谢
答案 0 :(得分:1)
你的第三只小猫派生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及更高版本中,您可以使用 rest参数:
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);
}
}