Home > Web Front-end > JS Tutorial > The difference between using prototype and not using prototype when defining functions in js class

The difference between using prototype and not using prototype when defining functions in js class

PHP中文网
Release: 2017-03-29 15:30:34
Original
1188 people have browsed it

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

cannot be called.
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template