have 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 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 these two methods? What's the effect of using no prototype?
Test code:
var t1=new ListCommon2 ("Boil 1", "Brew 1", "Drink 1"); T1.do1 ();//Call Error Listcommon2.do1 ("Boiling water 1"); var t2=new ListCommon2 ("Boil 2", "Brew 2", "Drink 2"); T2.do2 ("Boiling water 2");///Listcommon2.do2 ("boiling water 1");//Call Error
It has been tested that the method of not using prototype is equivalent to the static method of the class, so it can be called, listcommon2.do1 ("boiling water 1"), and if such a call would go wrong, t1.do1 ();
Conversely, the method of using prototype is equivalent to the instance method of the class, which is not allowed to be used after new, listcommon2.do2 ("boiling water 1");
It is concluded that the method defined with prototype is equivalent to the instance method of the class, which must be new before it can be used, and the restriction of the function may invoke the restriction of the instance method of the class somewhat similar
Using a method that does not use the prototype definition is equivalent to a static method of a class, which can be used directly, without the need for new, and the restriction of functions that can invoke a function is somewhat similar to the limitations of the static method method of a class
For example, this cannot be called. First ();