Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the main advantage of using prototype in javascript? [duplicate]

Tags:

javascript

function Candy(name) {
 this.name = name;
}
Candy.prototype.printName = function () {
 console.log(this.name);
}
var chocolate = new Candy("chocolate");
chocolate.printName();
var gummyBears = new Candy("gummy bears");
gummyBears.printName();

This does exactly the same thing as not using the prototype:

function Candy(name) {
  this.name = name;
  this.printName = function () {
    console.log(this.name);
  }
}
var chocolate = new Candy("chocolate");
chocolate.printName();
var gummyBears = new Candy("gummy bears");
gummyBears.printName();

So I’m not sure what the advantage of using a prototype instead is either!

like image 703
Sunil Yadav Avatar asked Oct 15 '22 21:10

Sunil Yadav


People also ask

What is the advantage of prototype in JavaScript?

Prototypes allow you to easily define methods to all instances of a particular object. The beauty is that the method is applied to the prototype, so it is only stored in the memory once, but every instance of the object has access to it.

What is the use of function prototype in JavaScript?

A Function object's prototype property is used when the function is used as a constructor with the new operator. It will become the new object's prototype. Note: Not all Function objects have the prototype property — see description. Note: The prototype property of classes is not writable.

What is prototype and __ proto __ in JavaScript?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.

What is the difference between prototype and object in JavaScript?

A prototype is just an object. It's any object that another object uses as it's prototype.


1 Answers

Here I am trying to give you an example to show you the advantage of prototype in JavaScript.

ex: Classes

Classes, Prototypes, Object Oriented JavaScript is a paradigm for structuring our complex code.

In JavaScript we use Prototype chain, a feature under the hood that enables emulation of OOP and which is a compelling tool in itself.

In new versions of javascript we use the new and class keywords to automate our object & method creation.

We use objects to represent real objects with their data and their functionalities. There is mainly 04 way to do so:

1. Each object store its own functions with its associated data.

This is the trivial and the easy solution, but its cons imagine we have two objects with same functionality => Whenever we create a new object we allocate space in the memory for all our data and functions while those functions are the same! Bad approach. That is why the second approach comes: Prototype chain; why we use prototypes".

2. Use the prototype chain:

check the code below:

function userCreator (name, score) {
 const newUser = Object.create(userFunctionStore); // to link to the the new created object to its functionalities
 newUser.name = name;
 newUser.score = score;
 return newUser;
};
const userFunctionStore = {
 increment: function(){this.score++;},
 login: function(){console.log("Logged in");}
 ...
};
const user1 = userCreator("user1", 3);
const user2 = userCreator("user2", 5);
user1.increment();

We Store the common function increment in just one object. So whence the new created user does not find the finction in its own object it will look via its generated link by Object.create() to functionStore and here it can get the function it looks for increment.

Note: All objects have a __proto__ property whcih by default links to a big object Object.prototype which have useful functions; like e hasOwnProperty method that check if an object has the given property; that we can access to it here via userFunctionStore’s __proto__ property.

Conclusion

Good approach but quite long and not standard.

3. Use new keyword to automates the hard work.

Look at the code below

function userCreator(name, score) {
    const newUser = Object.create(functionStore);
    newUser this.name = name;
    newUser this.score = score;
    return newUser;
   };
   functionStore userCreator.prototype // {};
   functionStore userCreator.prototype.increment = function(){
    this.score++;
   }
   const user1 = userCreator("user1", 3);

With the used of new keyword it will be resumed to

function userCreator(name, score) {
    this.name = name;
    this.score = score;
};
userCreator.prototype // {};
userCreator.prototype.increment = function(){
    this.score++;
}
const user1 = new userCreator("user1", 3);

So automatically new will do 03 main things:

  1. this: {} => Create automatically this empty object to assign the properties and values to it.
  2. __proto: userCreator.prototype => Add __proto__ hidden property to this new created object and link it to userCreator.prototype that is an object that store the common functions.
  3. return this => return this new created object.

Look at this code:

function userCreator(name, score){
    this.name = name;
    this.score = score;
}
userCreator.prototype.increment = function(){ this.score++; };
userCreator.prototype.login = function(){ console.log("login"); };
const user1 = new userCreator("user1", 3)
user1.increment()

Here is a simulation of the explanation above.

user1 = {
  name: 'user1',
  score: 3,
  __proto__: userCreator.prototype
}

userCreator = function + prototype =>

prototype = {
    increment: function(){ this.score++; },
    login: function(){ console.log("login"); }
}

Conclusion

Faster to write. Often used in practice in professional code. A Lot of developers do not know how it works. We have to upper case first letter of the function, so we know it requires new to work!

4. The class "syntactic sugar"

Write our shared (common) methods in the object creator itself. The code should be:

class UserCreator {
 constructor (name, score){
 this.name = name;
 this.score = score;
 }
 increment (){ this.score++; }
 login (){ console.log("login"); }
}
const user1 = new UserCreator("user1", 3);
user1.increment();

Conclusion

This approach is emerging as a new standard, and feels more like style of other languages (e.g. Python)

Very important this class keyword is just comes to remove the confusion using newkeywords but under the hoods it is absolutly working as same new key word. So do not get confused by other languages.

Reference

All credits go for this course JavaScript: The Hard Parts, v2.

like image 160
Ahmad Alsabbagh Avatar answered Oct 21 '22 14:10

Ahmad Alsabbagh