Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between Class Properties and Function Prototype in Javascript

Tags:

javascript

I like to learn the difference between Class Property and Prototype in Javascript what I mean is shown in the code :

function Rectangle(x, y) {
    this.width = x;
    this.height = y;
}

Rectangle.UNIT = new Rectangle(1, 1);

Rectangle.prototype.UNIT = new Rectangle(1, 1);

The thing I know is prototype is working like inherit object which means UNIT will be shown all the instances from now on but Rectangle.UNIT = new Rectangle(1, 1); code doesn't do the same thing ?

like image 476
Tarik Avatar asked Aug 31 '09 02:08

Tarik


1 Answers

Rectangle.UNIT is a static class property. It can only ever be accessed on the Rectangle class object. It won't be accessible on any instances of Rectangle.

Rectangle.prototype.UNIT is a prototype property and can be accessed on instances of Rectangle.

If you make a class Square that inherits from Rectangle, any instances of Square will share the same prototype property, but not any static class properties.

You may find these articles helpful (though maybe a little obscure):

  • http://phrogz.net/JS/Classes/OOPinJS.html
  • http://phrogz.net/JS/Classes/OOPinJS2.html
  • http://javascript.crockford.com/prototypal.html
like image 116
James Wheare Avatar answered Sep 19 '22 21:09

James Wheare