I have been using js to write self-righteous methods for objects . When I encountered a problem, I defined a method as follows:
The 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 does it do to use prototype or not?
Test code:
var t1= new ListCommon2("烧水1","泡茶1","喝1"); // t1.do1();//调用出错 ListCommon2.do1("烧水1"); var t2=new ListCommon2("烧水2","泡茶2","喝2"); t2.do2("烧水2");// // ListCommon2.do2("烧水1");//调用出错
After testing, it was found that the method without using prototype is equivalent to the static method of the class, so it can be called like this, ListCommon2. do1("Boiling water 1");, if called like this, an error will occur, t1.do1();
On the contrary, the method using prototype is equivalent to the instance method of the class, which cannot be used until new is allowed, ListCommon2. do2("Boil water 1"); This will cause an error
Conclusion, the method defined using prototype is equivalent to the instance method of the class, which must be used after new. Functions can be called in functions The restrictions will also be similar to the restrictions on the instance methods of the class.
Using methods that are not defined by prototype is equivalent to the static method of the class. It can be used directly without new, and the restrictions on the functions that can be called in the function will also be The restrictions on static methods of classes are somewhat similar to
. For example, this.First();