The difference between class.prototype.property and object.property

What is the point of using a prototype? If I create a class like -

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

now if i want to add a new property like p2

I do this prototype property for the class and do it on the object too, for example

using direct object →

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

using prototype →

myClass.prototype.p2 = 'p2';

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

+4
source share
1 answer

A prototype helps you to have a form of inheritance (prototype inheritance).
you can add properties to your objects manually or borrow a property from your prototype. Let's take a look at 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 let's see what happens with the myClass prototype:

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

And here is an example with non-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

: __proto__ {}, .

, .

+2

Source: https://habr.com/ru/post/1693294/


All Articles