The difference between a designer template and a prototype template

So, I'm trying to circle my head in various ways to create an object.

I went to the Protoype template for creating objects.

Now I have written two functions below, but I do not see what is the functional difference between them? When will you use the Constructor template and when will you use the Prototype template?

Constructor

function Fruit(){} Fruit.color = "Yellow", Fruit.fruitName = "Banana", Fruit.nativeTo = "SomeValue" 

Prototype template

 function Fruit(){} Fruit.prototype.color = "Yellow", Fruit.prototype.fruitName = "Banana", Fruit.prototype.nativeTo = "SomeValue" 
+7
javascript object
source share
3 answers

Repeatability of components ...

Constructor

When you create a new constructor, you will create a new instance of everything and, importantly, any changes made to the instances will only affect them, and not others.

Prototype

When you create a new object using a prototype, it will reuse the logic, and any change to the prototype chain will affect everyone else.

This is a nice explanation: prototyping and instantiating Javascript

When to use each template based on needs is a very ambiguous answer, but, nevertheless, the situation.

Think about the object, function, array that they use in JS, and it will make sense that they live in a prototype chain, like any changes we have for them that we would like to distribute - a side note: that’s why we never have to change them, as this can ruin their behavior.

The best explanation here: JavaScript constructors, prototypes, and the new keyword

+12
source share

Constructor

Basically, the constructor is used to create an object using the new operator.

He used to initialize the properties of the constructor instance. Thus, constrctor with new is nothing more than an implementation of a class that carries an object-oriented language, for example C ++, JAVA.

Each constructor has a prototype property that contains a reference to the constructor.

Prototype

Invalid class based class property.

In JavaScript, to implement inheritance we used prototype , which was used to implement one level of inheritance.

So, to achieve code reuse in JavaScript, a prototype is used. This is nothing but prototype inheritance.

In prototypical inheritance, a method or properties added to a prototype are immediately accessible to an object created from the same constructor

+2
source share

Changing the properties of the prototype will be applied to all instances, including existing ones, where, since changing the property that was created by the constructor will change it only for the instance

+1
source share