Example introduction of using prototype and not using prototype when defining function of js class

  • 2020-03-30 03:19:37
  • OfStack

Js has been used to write self-righteous object-oriented methods, encountered a problem, is to define a method, as follows:
 
function ListCommon2(first,second,third) 
{ 
this.First=function () 
{ 
alert("first do"+first); 
} 
} 
ListCommon2.do1=function(first) 
{ 
// this.First(); 
alert("first do"+first); 
} 
ListCommon2.prototype.do2=function(first) 
{ 
// this.First(); 
alert("first do"+first); 
} 

What's the difference? What's the use of prototype?

Test code:
 
var t1=new ListCommon2(" Boil water 1"," Make tea 1"," drink 1"); 
// t1.do1();// Call wrong  
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 wrong  

On test, the method that doesn't use prototype is equivalent to the static method of the class, so you can call listcommon2.do1 (" boil water 1"); , if so call will be wrong, t1.do1();

In contrast, using prototype's method is equivalent to the instance method of the class, which is not allowed to be used after new, listcommon2.do2 (" boil water 1"); That would be wrong

In conclusion, the method defined by prototype is equivalent to the instance method of the class, which can only be used after new, and the limitation of calling function in the function is similar to that of the instance method of the class

Using methods not defined by prototype is equivalent to the static method of the class, which can be used directly without the need for new, and the limitation of calling functions in the function is similar to the limitation of the static method of the class

For example, you cannot call this.first ();

Related articles: