0
\$\begingroup\$

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)?
\$\endgroup\$
2
  • 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
    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
    Jun 14, 2014 at 23:12

1 Answer 1

4
\$\begingroup\$
  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.

  2. 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.

  3. Unless you intend to create polymorphic classes, use the first one.

\$\endgroup\$
3
  • \$\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
    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\$
    – m93a
    Jun 15, 2014 at 12:49
  • 1
    \$\begingroup\$ @maja check this in chrome! jsperf.com/construct-proto/8 \$\endgroup\$ Jul 28, 2014 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.