Note: Original http://www.2cto.com/kf/201406/307790.html
Here as a study, written here
When writing JS scripts in an object-oriented way, there are two main ways to define An instance : this.xxx = function () p{and function.prototype.xxx= function () {}
function ListCommon2 (Afirst) { var first=afirst; This.do1=function () { alert ("First do" +first); } } Listcommon2.prototype.do2=function () { // alert ("First do" +first);//error, No access to first this.do1 (); By calling both the Do1 () method, the indirect access to the first property. }
What is the difference between this.do1=function () and listcommon2.prototype.do2=function ()?
is equivalent to the class instance method, only new can be used, then what is the difference?
Test code:
var t2=new ListCommon2 ("Boiling water 2"); T2.do1 ();// T2.do2 ();//
It has been tested that THIS.DO1 can access the variable first inside the constructor, but ListCommon2.prototype.do2 cannot access it, but can access the function This.do1.
If the ListCommon2.prototype.do2 is defined inside the constructor, it is also accessible .
function ListCommon2 (Afirst) { var first=afirst; This.do1=function () { alert ("First do" +first); } listcommon2.prototype.do2=function () { alert ("First do" +first);// defined internally, you can accessfirst //This.do1 (); } In fact, speaking ListCommon2.prototype.do2 written within the class is meaningless, so write This.do2 = directly. Yes, just like the do1 above.
therefore FUNCTION.PROTOTYPE.DO2 = function () {...}, which is generally written outside of the "class", is used to implement inheritance attributes to the class language (such as PHP), encapsulating the attributes. The Do2 () method is equivalent to a method inside a class (a method within a class, a method inside a class), and Do1 () is equivalent to a method defined in the class body (subclass, object). } Test code var t2=new ListCommon2 ("Boiling water 2"); T2.do1 ();// T2.do2 ();//
However, as an instance function, if it is defined inside the constructor, each instantiation is executed, obviously wasting memory, is not reasonable.
Some of the information on the This.do1 method is called the privileged method, mainly to access the internal private fields, so that you can control access to some fields. For example, a private field first is defined, and can only be passed through a constructor, and then it cannot be modified.
ListCommon2.prototype.do2 such methods are equivalent to instance methods of a class, but can access these privileged methods and indirectly access private fields.
Conclusion:
If you want to access private fields directly, you should use the privileged method, which is the method defined by this, which should be defined inside the constructor. Conversely, if you do not need direct access to private fields, you should use the method defined by prototype and should be defined outside the constructor.
JavaScript defines the function when this and prototype differ