I am practicing OOP in JavaScript while implementing inheritance I am getting an error of Uncaught type Error : sqr.area is not a function. In my code I have a BoxShape class from which a Square class is inherited. and I am trying to call the area function which is part of BoxShape using Square object and according to me its inherited to the square class as I have set its prototype the BoxShape class. But I am unable to figure out where is the mistake.
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());
lengthandwidthvariables anywhere? My tip: Avoid getters and setters until you need them. Just dothis.length = length; this.width = width;.