The difference between using prototype and not using prototype when defining functions in js

Reprinted from: https://blog.csdn.net/yexudengzhidao/article/details/72866047

Let's see an example

function ListCommon2(first,second,third) 
{
    this.First=function () 
    {
        alert("first do"+first); 
    }
}
// If no prototype is added, 
ListCommon2.do1= function (first)
{
    // this.First(); 
    alert("first do"+first); 
}
// In the case of adding prototype 
ListCommon2.prototype.do2= function (first)
{
    // this.First(); 
    alert("first do"+first); 
}

What is the difference between adding and not adding the prototype above? Let's test this example. code show as below

var t1= new ListCommon2("boil water 1", "brew tea 1", "drink 1" ); 
 // t1.do1();//call error 
ListCommon2.do1("boil water 1" ); 
 var t2= new ListCommon2("Boil water 2","Make tea 2","Drink 2" );
t2.do2( "Boil water 2"); //  
// ListCommon2.do2("Boil water 1");//Call error

After testing, it is found that the method that does not use the prototype is equivalent to the static method of the class, so it can be called like this, ListCommon2.do1("Boil water 1"); but if it is called in this way, an error will occur, t1.do1();

On the contrary, the method of using prototype is equivalent to the instance method of the class, which cannot be used after new, ListCommon2.do2 ("Boil water 1"); this will make an error

in conclusion:

  • The method defined using prototype is equivalent to the instance method of the class, which must be new before it can be used
  • A method defined without using prototype is equivalent to a static method of the class and can be used directly without new

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325287958&siteId=291194637