我试图使用继承,但是我被卡住了。我收到一个错误,不知道我做错了什么。我在网上看到的所有示例都不会将对象传递到构造函数中,所以我不确定我应该做什么。这里是一个简单化的例子 -JavaScript - 继承错误
function Automobile(obj){
this.name = obj.name;
this.model = obj.model;
}
Automobile.prototype = {
getName: function(){
console.log(this.name);
},
getModel: function(){
console.log(this.model);
}
}
var bmw = new Automobile({
name: 'BMW',
model: 'm5'
})
bmw.getName();
bmw.getModel();
function Truck(obj){
this.cabSize = obj.cabSize
}
Truck.prototype = new Automobile();
Truck.prototype = {
getCabSize: function(){
console.log(this.cabSize);
}
}
var fordF150 = new Truck({
name: 'Ford',
model: 'F150'
})
//Uncaught TypeError: Cannot read property 'name' of undefined test.js:2
//Automobile test.js:2
//(anonymous function)
当你调用'Truck.prototype = new Automobile();你期望第一个参数是一个对象时,你还没有传递一个对象。 – Musa 2014-08-28 23:16:15