I have been using js to write self-built object-oriented methods. One problem is to define a method as follows:
Copy codeThe Code 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?
Test code:
Copy codeThe Code is as follows:
Var t1 = new ListCommon2 ("boiling water 1", "Tea 1", "drinking 1 ");
// T1.do1 (); // call error
ListCommon2.do1 ("boiling water 1 ");
Var t2 = new ListCommon2 ("boiling water 2", "Tea 2", "drinking 2 ");
T2.do2 ("boiling water 2 ");//
// ListCommon2.do2 ("boiling water 1"); // call error
After testing, we found that the prototype method is not used as the static method of the class, so we can call ListCommon2.do1 ("boiling water 1");. If so, an error occurs, t1.do1 ();
On the contrary, the prototype method is equivalent to the instance method of the class, which can only be used after the new method is not allowed. ListCommon2.do2 ("boiling water 1"); in this case, an error occurs.
Conclusion: The method defined by prototype is equivalent to the instance method of the class and can only be used after it is new. The restrictions on the instance method of the class that can be called in functions are similar.
If you do not use a method defined by prototype, it is equivalent to a static method of the class. You can use it directly without the need for new methods. The restrictions on the static method of the class that can be called in functions are also similar.
For example, you cannot call this. First ();