Js Object-Oriented Programming: What is the difference between prototype and this when js class defines functions?

Source: Internet
Author: User

When writing js scripts in object-oriented mode, there are two methods to define an instance:

As follows:

Function ListCommon2 (afirst) {var first = afirst; this. do1 = function () {alert ("first do" + first) ;}} ListCommon2.prototype. do2 = function () {// alert ("first do" + first); // an error occurs and you cannot access firstthis. do1 ();}

This. do1 = function () and ListCommon2.prototype. do2 = function () What is the difference?

It is equivalent to the instance method of the class and can only be used after new. What is the difference?

Test code:

Var t2 = new ListCommon2 ("boiling water 2"); t2.do1 (); // t2.do2 ();//

After testing, we found that this. do1 can access the variable first in the constructor, while ListCommon2.prototype. do2 cannot access this. do1.

If you define ListCommon2.prototype. do2 In the constructor, you can access it. However, as an instance function, if it is defined inside the constructor, It will be executed every time it is instantiated. Obviously, it is a waste of memory and it is unreasonable.


In some documents, this. do1 is called a privileged method. It is mainly used to access private fields, so that access to certain fields can be controlled. For example, a private field first is defined as above. It can only be passed through the constructor and cannot be modified.

ListCommon2.prototype. do2 is equivalent to the instance method of the class, but can access these privileged methods and indirectly access private fields.


Conclusion:

If you want to directly access private fields, you should use the privileged method, that is, the method defined by this, which should be defined within the constructor. On the contrary, if you do not need to directly access private fields, you should use the method defined by prototype and define it outside the constructor.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.