Whenever I needed something similar like a "Class" in JavaScript, I wrote it like this:
function Point(x, y){
var self = this;
self.x = x;
self.y = y;
self.dist = function(){
return Math.sqrt( (self.x*self.x) + (self.y*self.y) );
}
}
var p = new Point(10, 20);
p.x = 30;
alert(p.dist);
I declared a function and wrote the constructor directly into it. Public variables and methods have the self.
-operator in front of it.
Now I took a look at TypeScript, which declares the exact same function this way:
var Point = ( function(){
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.dist = function(){
return Math.sqrt( (this.x*this.x) + (this.y*this.y) );
}
return Point;
})();
var p = new Point(10, 20);
p.x = 30;
alert(p.dist());
This definition makes use of a closure, and uses prototype
.
My Questions:
- What are the advantages/disadvantages of the 2 definitions?
- Which method is more efficient?
- Which method should I prefer to use (when I don't use TypeScript)?
-
3\$\begingroup\$ This question seems offtopic, and there many duplicates on StackOveflow. Bottomline, the first one duplicates methods for each new instance, while the second one shares prototype methods between instances. \$\endgroup\$elclanrs– elclanrs2014年06月14日 19:31:45 +00:00Commented Jun 14, 2014 at 19:31
-
1\$\begingroup\$ Agreed. I'd just add that the IIFE in the second example is completely unnecessary. \$\endgroup\$Dagg– Dagg2014年06月14日 23:12:02 +00:00Commented Jun 14, 2014 at 23:12
1 Answer 1
Using prototype is useful for polymorphism. If you want to create another class, eg.
ColourfulPoint
, you can use this code:ColourfulPoint.prototype = Object.create(Point.prototype);
to make your new class inherit all the methods of
Point
.The first method (using only a constructor) is a way faster (at least in Firefox and Chrome) than the prototype one. Take a look at the test.
Unless you intend to create polymorphic classes, use the first one.
-
\$\begingroup\$ That's really a huge performance difference. Now I'm not sure anymore, if switching/porting to TypeScript is the best choice \$\endgroup\$maja– maja2014年06月15日 09:45:07 +00:00Commented Jun 15, 2014 at 9:45
-
\$\begingroup\$ But in another test by @DaggNabbit, prototype reaches similar results or even wins: jsperf.com/construct-proto/2 - strange... \$\endgroup\$a pfp with melon– a pfp with melon2014年06月15日 12:49:19 +00:00Commented Jun 15, 2014 at 12:49
-
1\$\begingroup\$ @maja check this in chrome! jsperf.com/construct-proto/8 \$\endgroup\$Mark Robbins– Mark Robbins2014年07月28日 20:50:05 +00:00Commented Jul 28, 2014 at 20:50
Explore related questions
See similar questions with these tags.