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.