[英]Uncaught Type Error while implementing inheritance in javascript
我在实现继承时正在JavaScript中练习OOP,但遇到了Uncaught类型的错误错误:sqr.area不是函数。 在我的代码中,我有一个BoxShape类,从该类继承了Square类。 我试图使用Square对象调用BoxShape的一部分的area函数,并且根据我的看法,因为我将其原型设置为BoxShape类,所以继承了Square类。 但是我无法弄清楚哪里出了问题。
function show(msg){
console.log(msg);
}
function BoxShape(){
Object.defineProperty(this,'length',{
get: function(){
return length;
},
set: function(val){
length = val;
},
enumerable : true,
configurable:true
});
Object.defineProperty(this,'width',{
get:function(){
return width;
},
set:function(val){
width=val;
},
configurable : true,
enumerable : true,
});
this.area=function(){
return this.width*this.length;
}
}
//inherited square class
function Square(size){
Object.defineProperty(this,'width',{
get: function(){
return width;
},
set: function(val){
width = val;
},
configurable: true,
enumerable:true,
});
Object.defineProperty(this,'length',{
get:function(){
return length;
},
set:function(val){
length=val;
},
configurable:true,
enumerable:true,
});
}
Square.prototype = Object.create(BoxShape.prototype,{
constructor:{
configurable:true,
enumerable:true,
writable:true,
value:Square
}
});
var sqr = new Square();
sqr.length = 10;
sqr.width = 12;
show(sqr.area());
您的错误是,您将函数定义为实例属性(对于每个实例都是独立的)而不是原型属性(对于所有实例都是相同的,并且直接继承)。
正如Bergi所述,由于您的getter和setter并没有做任何事情,因此直接在构造函数中直接分配这些属性会更容易。
最后但并非最不重要的一点是,您可能想在Square
构造函数内部调用BoxShape
构造函数以初始化width
和height
道具。
function show(msg){
console.log(msg);
}
function BoxShape(){
this.width = 0;
this.height = 0;
}
BoxShape.prototype.area=function(){
return this.width*this.length;
}
//inherited square class
function Square(size){
BoxShape.call(this);
}
Square.prototype = Object.create(BoxShape.prototype,{
constructor:{
configurable:true,
enumerable:true,
writable:true,
value:Square
}
});
var sqr = new Square();
sqr.length = 10;
sqr.width = 12;
show(sqr.area());
您没有将BoxShape
的原型设置为具有该方法。 执行此操作时,可以将每个实例设置为具有该方法的自己的实例:
// this.whatever is instance specific, which isn't what you want in your case
this.area=function(){
return this.width*this.length;
}
那不是原型。
你应该做:
BoxShape.prototype.area = function() {
return this.width*this.length;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.