has been using JS to write self-righteous object-oriented approach, encountered a problem, is to define a method, as follows:
Copy Code code as follows:
function ListCommon2 (First,second,third)
{
This. First=function ()
{
Alert ("+first");
}
}
Listcommon2.do1=function (a)
{
This. A ();
Alert ("+first");
}
Listcommon2.prototype.do2=function (a)
{
This. A ();
Alert ("+first");
}
What is the difference between the two methods? What's the use of not prototype?
Test code:
Copy Code code as follows:
var t1=new ListCommon2 ("Boil water 1", "Tea 1", "Drink 1");
T1.do1 ()//Call Error
Listcommon2.do1 ("Boil water 1");
var t2=new ListCommon2 ("Boil water 2", "Tea 2", "Drink 2");
T2.do2 ("Boiling water 2");
Listcommon2.do2 ("Boil water 1");/Call Error
The test found that the method of not using prototype is equivalent to the static method of the class, so it can be called listcommon2.do1 ("boil water 1"), if this call will be wrong, t1.do1 ();
Instead, the method of using prototype is equivalent to an instance method of a class, which is not allowed to be used until new, listcommon2.do2 ("boil water 1");
conclusion, the method defined by using prototype is equivalent to an instance method of a class, which must be new before it can be used, and the restriction of the function in which the function may be invoked may also be somewhat similar to the limitations of the instance method of the class
Using a method that does not use the prototype definition is equivalent to a static method of a class that can be used directly, without the need for new, a function in which a function can invoke a limit of the method of the class also has some similar limitations
For example, you cannot call this. A ();