我现在正在学习JS继承,有一些不清楚的地方。 考虑以下代码:
function Mammal(pName){
var name = pName; //"private" variable name
this.getName = function(){ //return name via closure
return name;
}
this.mammalStuff = function(){
console.log("im a mammal!!");
}
}
Mammal.prototype.speak = function(){
console.log("im a "+ this.getName()+" !") //every Mammal can speak
}
function Cat(){
this.catStuff = function(){
console.log("cat says mew");
}
}
Cat.prototype = new Mammal(); //All cat objects inherit all Mammal characteristics
var houseCat = new Cat("Kittie");
现在,houseCat
可以访问 mammalStuff
和 catStuff
属性。现在,在当前的代码配置中,每当我调用 getName
\speak
方法时,houseCat
都会打印 undefined
。为什么我不能直接使用 name
属性的父类构造函数?
最佳答案
当你请求 JS 对象的属性时,JS 会遍历原型(prototype)链,直到找到该属性。因此对象继承自它们的原型(prototype)。
构造函数只是一个函数。当执行一个函数(Cat 的构造函数)时,没有规则同时调用其他函数(Mammal 的构造函数)。
您可以明确强制执行此操作。例如
function Cat(name){
Mammal.call(this, name);
this.catStuff = function(){
console.log("cat says mew");
}
}
关于JavaScript继承机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28027707/