JavaScript is not a class orientated programming language. However, there are some approaches to create object instances in JavaScript. I've read one such way is a function constructor approach to create "instances" and one way is this:
function Circle(radius) {
this.radius = radius;
Circle.prototype.area = function () {
return this.radius * this.radius * 3.14
}
}
smallWheel = new Circle(2); bigWheel = new Circle(5);
smallWheel.area == bigWheel.area => True;
Isn't there an inefficiency in that Circle.prototype.area
is reset again to the same function "string" function () { return this.radius * this.radius * 3.14
when you invoke Circle(2)
and Circle(5)
?
Although it sets the same value over, isn't it inefficient? Imagine having hundreds of instances... and this can be inefficient?
From my understanding normal OO languages wouldn't need to compile functions over and over for an instance as it is shared. Can anyone clarify?
Edit: It was an oversight from my part , I missed a '}' in the next line after the function body . However the answer below is helpful especially the part that it should be defined outside and this.area is inefficient .