The transformation from purely Object-oriented Thinking (Java thinking) to Object-oriented Thinking in Javascript language has experienced severe pain. The concept conversion of objects and classes in Javascript is confusing. Sometimes, the clearer Java is, the harder it is to understand JavaScript. It is especially time-consuming to understand the prototype objects of JavaScript.
By definition, each JavaScript Object has a prototype (prototype) defined by the constructor of the object (automatically created by JavaScript ), and the object inherits all attributes and methods (functions) of the prototype. For example, the prototype of a string object is string. prototype. If you want to add a method to the string class, you can do this (for example, add a common trim () method ):
JS Code
- String. Prototype. Trim = function (){
- Return this. Replace (/(^/S *) | (/S * $)/g ,"");
- }
This feature is quite surprising, because it destroys encapsulation, just as you can directly modify the string class in Java. Function () can be used as data to assign values to the left operand (not just as an action). It is also very different from Java.
You can change the internal classes of Javascript in this way. You can change the internal classes of custom classes as follows:
JS Code
- Function circle (X, Y, R ){
- This. x = X;
- This. Y = y;
- This. r = R;
- // This. prototype = NULL;/* The Code can be considered as implicit. Because there is no difference between the definition of "class" in JavaScript and the definition structure of the function, we can say that, all functions have such an attribute hidden. */
- }
Then, we add an Area Method to the prototype:
- Circle. Prototype. Area = function (){
- Return this. R * This. R * 3.14159;
- }
It can be used as follows:
JS Code
- VaR CIRC = new circle (0, 0, 2 );
- Alert (CIRC. Area ());
Of course, we can also easily define the method we want to implement in the class, for example, to calculate the circular area above:
JS Code
- Function circle (X, Y, R ){
- This. x = X;
- This. Y = y;
- This. r = R;
- This. Area = function (){
- Return this. R * This. R * 3.14159;
- }
- }
- // Call:
- VaR CIRC = new circle (0, 0, 2 );
- Alert (CIRC. Area ());
The call code of the two is the same. Why should we use the prototype? I think it is mainly to solve the internal type inheritance problem. That is to say, when you cannot modify the string constructor and want to make all string instances have a certain method, you can use this prototype; Or, you can use this prototype to simulate the implementation of the subclass of the string class to expand the parent class.
Http://metaphy.javaeye.com/blog/91665 (former blog)