Class-Definition Comparison 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)?
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.