4

what is the significance of using prototype ? If i make a class as -

var myClass = function(){ this.p1 = 'p1';}

now if i want new property to be added as p2

i do it prototype property for the class and do it on object as well, like

using direct object ->

var obj = new myClass();
obj.p2 = 'p2';

using prototype ->

myClass.prototype.p2 = 'p2';

how these two are different? or are both lines different ?

2
  • Try to make two instances of your class and give the p2 property different values. You'll immediately spot the difference. Commented Feb 7, 2018 at 5:14
  • thanks ! got the difference Commented Feb 7, 2018 at 5:43

1 Answer 1

2

Prototype helps you, to have kind of inheritance (prototypal inheritance).
you can add properties to your objects manually, or borrow the property from its prototype. Let's take a look to some examples:

var obj = new myClass();
obj.p2 = 'p - child';
console.log(obj.p2); // p - child

var obj2 = Object.assign(obj.__proto__); // will borrow the value from the obj prototype
console.log(obj.p2); // p - child

Now take a look to what happen with myClass prototype:

var obj3 = Object.assign(myClass.prototype); //will borrow the value from the myClass prototype
console.log(obj3.p2); // p - parent

And here an example with not existing properties:

var obj4 = new myClass();
var obj5 = Object.assign(obj4.__proto__);

obj4.p3 = 'P3 - value';

console.log(obj4.p3); // P3 - value
console.log(obj5.p3); // undefined

Note: __proto__ is for objects {}, prototype is for functions.

Hope this helps to clarify a little bit.

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

1 Comment

Please do not use the deprecated __proto__ getter in explanations any more. Always use Object.getPrototypeOf.

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.