The method that does not use prototype is equivalent to the static method of the class. On the contrary, the method that uses prototype is equivalent to the instance method of the class. It cannot be used until new is allowed.
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("Boil 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 can only be used after new is not 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. The restrictions on the functions that can be called in the function are also similar to the restrictions on the instance methods of the class
Using methods that do not use prototype definitions is equivalent to static methods of the class. They can be used directly without new. The restrictions on functions that can be called in the function are also similar to the restrictions on the static methods of the class.
For example, this.First();
The above is the detailed content of Detailed explanation of code examples of the difference between javascript using and not using prototype. For more information, please follow other related articles on the PHP Chinese website!