I have been using js to write self-righteous object-oriented methods. I encountered a problem, which is to define a method, as follows:
The code copy is 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 is the difference between the two methods? What is the function of using prototype or not?
Test code:
The code copy is as follows:
var t1=new ListCommon2("boil water 1","brew tea 1","drink 1");
// t1.do1();// An error occurred when the call
ListCommon2.do1("boiled water 1");
var t2=new ListCommon2("boil water 2","buy tea 2","drink 2");
t2.do2("boiling water 2");//
// ListCommon2.do2("Boiling Water 1");// An error occurred in call
After testing, it was found that the method that did not use prototype is equivalent to the static method of the class, so it can be called in this way, ListCommon2.do1("boiling water 1");, if it is called in this way, an error will occur, t1.do1();
On the contrary, the method using prototype is equivalent to the instance method of the class and cannot be used after new. ListCommon2.do2("boil water 1"); this will cause an error.
Conclusion: The method defined using prototype is equivalent to the instance method of a class and must be used after new. The limitations of the function that can be called in the function will also be similar to the limitations of the instance method of a class.
Using methods defined without using prototype is equivalent to static methods of the class. You can use them directly without new. The restrictions of functions that can be called in functions will also be similar to the limitations of static methods of the class.
For example, this.First() cannot be called;