10

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 ?

3 Answers 3

19

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

Sign up to request clarification or add additional context in comments.

1 Comment

Can you elaborate this a little bit more please : "Static properties can vary between classes that share a given prototype inheritance chain."
2

Class-Based vs. Prototype-Based Languages @ Mozilla Developer Center. Neat!

Comments

1

Rectangle.UNIT is like a class static member, whereas Rectangle.prototype.UNIT is a local member. Looks like you want Rectangle.UNIT in your case, because you only need one static instance of the object.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.