What is prototype method in javascript

Meaning of prototype in javascript

When you put something on the prototype, every instance of the object shares the same code for the method. They are all using the same function instance.

When you simply put a method on this , every object instance has its own copy of the same method.

Using prototype is much more efficient. Note this is why typically methods are placed on the prototype, since you typically want all instances to use the same method, but properties are placed on the instance itself, because typically you don’t want all instances to share the same properties.

For your comment, if you put a method on the constructor function of an object, then you have in effect created a «static» method. No instance of the object will have that method, they all must access it on the constructor function. So in your case, Person.someMethod() .

I don’t know that there is a difference in the outcome (I don’t know about technically), adding to the Person function implies that you used the function constructor pattern. Also, with the use of Person.prototype you can add things to the Object definition later on in your program, not specifically to Person = function () <> at the time it is defined.

can you give me a short code example about the constructor function object? mean which you have said in the last paragraph? I’m new to javascript that’s why didn’t understand by theory. if you put a method on the constructor function of an object, then you have in effect created a «static» method

Читайте также:  Java зачем нужны поразрядные операции

When you put the method in the constructor and create an object out of that constructor, each object carries it’s own getName function. For 10 Person instances, each carries it’s own getName , therefore 10 separate getName functions.

If you place getName in the prototype of the constructor, that same getName function is shared/inherited across all instances. so for 10 instances of Person , each has getName but refer only to 1 getName function.

Using prototypes saves memory since the method is shared across instances so only one is used.

The difference is that when you put it on the prototype, all instances of Person share the same code for getName — you can change getName on all instances of Person by assigning something else:

Person.prototype.getName = function() < return 'Mr Jones' >; 

Also, since they share the same code, it’s less memory intensive: You only have one copy of the getName function, instead of one copy per instance.

Another difference is that you can later set the Person as the prototype of another class, let’s say Man , and it will inherit the properties/methods.

Update: Here is a good post explaining other properties of prototypes: https://stackoverflow.com/a/1534286/295262

Why should someone set the Person prototype as the prototype of Man? When comes to inheritance, shouldn’t it be in the form Man.prototype = new Person(); instead of Man.prototype = Person.prototype?

The difference is that is you further extend the Person class the sub classes will not inherit the getName() method

Edit: I was not correct in above statement. Just tested on the jsfiddle. Regardless of if we define a method on the prototype or on the function instance itself, it is available for the subclasses in the chain.

I understand that there is a performance/memory benefit of attaching the methods to prototype. Appart from that isn’t there any behavioral difference when it comes to inheritance?

(hopefully I’m not violating SO rules by asking a question here)

In class-based words the difference between declaring a function via prototype and this would be something like this:

the function of the instance would look like this:

the function of the instance would look like this:

Now changing the function on the prototype will have no effect on the instance.

When you add any function with this.functionname to any object constructor every object created by that constructor makes their own copy of that function which also takes memory. Imagine if you have several objects created by same constructor and how much memory it will take. on other hand when you creates it with cunstructorName.prototype.functionName function loads only once in memory and every object shares same prototype function constructor. this approach makes your code faster in loading and operation and also saves a big chunk of memory.

First of all understand few concepts before looking at javascript prototypes:

  1. Constructors: So basically in javascript any function that is called with a new keyword acts as a constructor and will return an object.
  2. this keyword inside the constructor: So when you use this keyword inside a function and then call that function with a new keyword. That this keyword is implicitly binded with that returned object and if you assign any property or method to this keyword, it will be assigned to that returned object. As shown in code sample provided below:
function foo() < this.name="foo" this.greet=function()< console.log("Good morning") >> const obj=new foo() 

So now if you want to have some property that will stay the same for all objects created, Then it doesn’t make sense to assign that property or method separate memory for each object instance. Rather you can define it on the prototype property of the constructor and then it will be accessible to all the objects created using that constructor. For example in sample given above greet method will stay same for all objects , So we can refactor as shown below:

function foo() < this.name="foo" >foo.prototype.greet=function() < console.log("Good morning") >const obj=new foo() 

It’s not inheritance.

Some people might depict it as an inheritance. But don’t get confused, It’s not your classical inheritance. But instead, it is delegation. So in the above code sample when you try to call the greet method w.r.t to obj . Interpreter says he can’t find it. So he will look at to which prototype this object is pointing. It will be pointing to the foo function’s prototype. So it will look into it and will find greet method defined there.

Источник

Prototype in JavaScript

Arunkumar Chandra

Enroll in Selenium Training

A prototype is an existing inbuilt functionality in JavaScript. Whenever we create a JavaScript function, JavaScript adds a prototype property to that function. A prototype is an object, where it can add new variables and methods to the existing object. i.e., Prototype is a base class for all the objects, and it helps us to achieve the inheritance. In this article, we will cover the following aspects of the JavaScript Prototype:

  • What is the Prototype in JavaScript?
    • When to use the prototype in JavaScript?
    • How to add variables to an object using the prototype in JavaScript?
    • How to add methods to the object using the prototype in JavaScript?

    What is the Prototype in JavaScript?

    As discussed, a prototype is an inbuilt object where it associated with the functions by default, which can be accessible, modifiable, and create new variables and methods to it and share across all the instances of its constructor function.

     Prototype object in JavaScript

    When to use Prototype in JavaScript?

    As we all know, Javascript is a dynamic language where we can add new variables and methods to the object at any point in time, as shown below.

    function Employee( ) < this.name = 'Arun'; this.role = 'QA'; > var empObj1 = new Employee(); empObj1.salary = 30000; console.log(empObj1.salary); // 15 var empObj2 = new Employee(); console.log(empObj2.salary); // undefined 

    As we see in the above example, the salary variable adds to the empObj1. But when we try to access the salary variable using the empObj2 object, it doesn’t have the salary variable because the salary variable is defined only in the empObj1 object.

    Now comes the question, Can there be a way that the new variable can be added to the function itself so as it is accessible to all the objects created using the function?

    The answer to this question is the use of a prototype. A prototype is an invisible inbuilt object which exists with all the functions by default. The variables and methods available in the prototype object can be accessible, modifiable, and even can create new variables and functions.

    We can attach a new variable or method to the object using proto keyword, as shown below:

     How prototype works in JavaScript

    Now, let’s see some practical implementations of how to add new variables and methods using the prototype functionality:

    How to add variables to an object using the Prototype in JavaScript?

    As discussed, there can be a time when we need to add the new variables to an existing object, which is almost impossible in other programming languages. But in javascript, we can achieve with the help of the prototype. It follows the following syntax for adding a new variable:

    ClassName.prototype.variableName = value; 

    Let’s understand the usage of «prototype» to add a new variable with the help of the following example:

    html> body> Demonstrating prototype for variables in javascript br> br> script type = "text/javascript"> function details( )< this.website="Tools QA", this.language="Java Script" > var tutorails = new details(); document.write(tutorails.website); document.write("
    "
    ); document.write(tutorails.language); details.prototype.Author = "Arunkumar Chandra"; document.write("
    "
    ); document.write(tutorails.Author);
    script> body> html>

    Save the file with name prototypeVariable.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as

     Using Prototype in variables

    As we can see from the above example, we added a new variable «Author» to the existing function «details«, and the same was accessible on the object «tutorials» later on.

    How to add methods to the object using the Prototype in JavaScript?

    Similar to the variables, sometimes, we need to add the methods for the existing object. The same can be achieved in JavaScript using the prototype functionality. Its syntax looks like below:

    className.prototype.functionname = ()=>< >; 

    Let’s understand the usage of «prototype» to add a new method with the help of the following example:

    html> body> Demonstrating prototype for method in javascript br> br> script type = "text/javascript"> function details( )< this.website="Tools QA", this.language="Java Script" > var tutorails = new details(); document.write(tutorails.website); document.write("
    "
    ); document.write(tutorails.language); details.prototype.Author = ()=>< return "Arunkumar Chandra"; >; document.write("
    "
    ); document.write(tutorails.Author());
    script> body> html>

    Save the file with name prototypeMethods.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

     Using Prototyping in Method

    In the above example, We are adding the «Author» method after the object is created and invoked it on the existing object «tutorials«.

    So, this way, we can add new variables and methods to the existing objects dynamically, which will be accessible to all the objects created using the function.

    Key Takeaways

    • A prototype is an object which associates with all the functions. Additionally, it is invisible, but all the properties inside the prototype are accessible.
    • When a programmer needs to add new properties like variables and methods at a later point of time, and these properties need sharing across all the instances, then the prototype will be very handy.
    • The prototype can add both variables and methods to an existing object dynamically.

    Let’s now move to the next article to understand some of the advanced features provided by JavaScript, such as Destructuring.

    Источник

Оцените статью