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)?