Home > Web Front-end > JS Tutorial > body text

Detailed explanation of code examples of the difference between javascript using and not using prototype

伊谢尔伦
Release: 2017-07-27 13:34:19
Original
1229 people have browsed it

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); 
}
Copy after login

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");//调用出错
Copy after login


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();

cannot be called

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!