has been using JS to write self-righteous object-oriented approach, encountered a problem, is to define a method, as follows:
function ListCommon2 (First,second,third)
{this
. First=function ()
{
alert (' +first ');
}
Listcommon2.do1=function (a)
{
//this . A ();
Alert ("the" +first);
}
Listcommon2.prototype.do2=function (a)
{
//this. A ();
Alert ("the" +first);
}
What is the difference between the two methods? What's the use of not prototype?
Test code:
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 ("Boil water 2");///
Listcommon2.do2 ("boiling 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 can only be used after 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 ();
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/