In the JavaScript the same thing you can do in many different ways.
Consider the examples:
1:
function Circle(radius) {
return {
"r" : radius,
"area" : function(){
return Circle.pi * this.r * this.r;
}
}
}
Circle.pi = 3.14159;
var a = Circle(10);
alert(a.area());
2:
function Circle(radius) {
this.r = radius;
}
Circle.pi = 3.14159;
Circle.prototype.area = function(){
return Circle.pi * this.r * this.r;
}
var a = new Circle(10);
alert(a.area());
The second is better than first because we dont define the same function area for any instance of the Circle.
But lets consider 3:
function Circle(radius) {
return {
"r" : radius,
"area" : Circle.area
}
}
Circle.pi = 3.14159;
Circle.area = function(){
return Circle.pi * this.r * this.r;
}
var a = Circle(10);
alert(a.area());
Is there any reason to prefer second style instead of third? Or I misunderstood something at all?
I would definitely go with example 2. Neither example 1 or 3 make good use of JavaScript's object-oriented features because:
this
, you lose the identity of the class, i.e. you can no longer do checks like a instanceof Circle
.Is there any reason to prefer second style instead of third?
The third style is still wasting a small amount of space in order to store the association between the name area
and the area function.
Also because you are returning a new Object
from the {...}
literal, instanceof Circle
won't work.
The second is better than first because we dont define the same function area for any instance of the Circle.
Indeed, but it can sometimes be useful to define a new copy of each method—a copy that, thanks to closures, can know what object it is bound to. With traditional prototyping you only get the this
context which is set from the object the caller retrieved it from, rather than bound to a particular object. The first way avoids the problems of this
-retention in things like event handlers, at the price of some loss of efficiency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With