Prototype attribute interpretation and common methods of JS

Source: Internet
Author: User
Tags prototype definition

This article Reprinted from: http://blog.sina.com.cn/s/blog_7045cb9e0100rtoh.html

 

Function: Prototype

Each constructor has a prototype attribute (prototype, which is not translated in the following example and is used in the original document ). This attribute is very useful: declare a common variable or function for a specific class.

Prototype Definition

You do not need to explicitly declare a prototype attribute because it exists in every constructor. You can look at the following example:

Example pt1

Code:

Function Test () {} alert (test. Prototype); // output "object"

Add properties to prototype

As you can see above, prototype is an object, so you can add attributes to it. The property you add to prototype will become a common property of the object created using this constructor.

For example, I have a data type fish below, and I want all fish to have these attributes: livesin = "water" and price = 20; to achieve this, I can add those attributes to the prototype of the constructor fish.

Example pt2

Code:

function Fish(name, color){this.name=name;this.color=color;}Fish.prototype.livesIn="water";Fish.prototype.price=20;

Next let's make a few fish:

Code:

For (INT I = 1; I <= 3; I ++) {var fish = eval_r ("fish" + I ); // I just get the pointer alert (fish. name + "," + fish. color + "," + fish. livesin + "," + fish. price );}

The output should be:

Code:
"Macarel, gray, water, 20"
"Goldfish, orange, water, 20"
"Salmon, white water, 20"

 

You can see that all fish have the attributes livesin and price, and we didn't even specifically declare these attributes for each different fish. In this case, when an object is created, this constructor will assign its property prototype to the internal attribute _ PROTO _ of the new object __. This _ PROTO _ is used by this object to find its attributes.

 

You can also use prototype to add common functions to all objects. This has one benefit: you do not need to create and initialize this function every time you construct an object. To explain this, let's repeat example dt9 and rewrite it using prototype:

 

Add a function to an object using prototype

 

Example pt3

 

Code:

function Employee(name, salary){this.name=name;               this.salary=salary;}Employee.prototype.getSalary=function getSalaryFunction(){return this.salary;}Employee.prototype.addSalary=function addSalaryFunction(addition){this.salary=this.salary+addition;}

 

We can create objects as usual:

Code:

VaR boss1 = new employee ("Joan", 200000); var boss2 = new employee ("Kim", 100000); var boss3 = new employee ("Sam", 150000 ); // verify it: // code: Alert (boss1.getsalary (); // output 200000 alert (boss2.getsalary (); // output 100000 alert (boss3.getsalary ()); // output 150000

 

Here is an illustration to illustrate how prototype works. Every instance of this object (boss1, boss2, boss3) has an internal attribute named _ PROTO __, which points to the prototype of its constructor (employee. When you execute getsalary or addsalary, this object will find and execute this code in its _ PROTO. Note: No code is copied here (compared with the chart example dt8 ).

 

 

 

 

 

Next is another article: http://www.cnblogs.com/anjey/archive/2012/02/14/2350431.html


I. Prototype And Constructor

All functions of JS have a prototype attribute, which references an object (prototype. This function includes constructor and common function. We are talking about the prototype of the constructor, but we cannot deny that common functions also have the original type. For example, common functions:

function F(){   alert(F.prototype instanceof Object) //true; }

Constructor, that is, the constructor object. First, understand the process of instantiating an object through the constructor.

function A(x){   this.x=x; } var obj=new A(1);

There are three steps to instantiate an OBJ object:

1. Create an OBJ object: OBJ = new object ();

2. point the internal _ PROTO _ of OBJ to construct the prototype of function A. At the same time, obj. constructor =. prototype. constructor (this is always true, even if. prototype no longer points to the original prototype a, that is, the constructor attribute of the Instance Object of the class always points to the prototype of the "constructor. constructor) to make obj. constructor. prototype points to. prototype (obj. constructor. prototype =. prototype, when. prototype is not valid when it is changed. We will see it below ). OBJ. constructor. prototype and internal _ PROTO _ are two different things. when instantiating an object, _ PROTO _ is used. OBJ has no prototype attribute, but internal _ PROTO __, the prototype attributes and prototype methods on the prototype chain are obtained through _ PROTO __. Firefox exposes _ PROTO __. you can use alert (obj. _ PROTO __);

3. Use OBJ as this to call constructor A, so as to set members (that is, object attributes and object methods) and initialize them.


When the three steps are completed, the OBJ object will no longer be associated with constructor A. In this case, even if constructor A adds any member, the instantiated OBJ object will no longer be affected. In this case, the OBJ object has the X attribute and all the members of the prototype object of constructor A. Of course, the prototype object has no members.

The prototype object is empty at first, that is, there is no Member (that is, the prototype attributes and prototype methods ). You can verify the number of members of a prototype object by using the following methods.

VaR num = 0; For (O in. prototype) {alert (o); // alert indicates the prototype property name num ++;} alert ("member:" + num); // alert indicates the number of all prototype members.

However, once a prototype attribute or prototype method is defined, all objects instantiated by the constructor inherit these prototype attributes and prototype methods, this is achieved through the internal _ PROTO _ chain.

A.prototype.say=function(){alert("Hi")}; 

All objects of a have the say method. The say method of the prototype object is the only copy shared by everyone, rather than a copy of The say method for each object.

 

Ii. prototype and inheritance 

First, let's look at a simple inheritance implementation.

1 function A(x){ 2   this.x=x; 3 } 4 function B(x,y){ 5   this.tmpObj=A; 6   this.tmpObj(x); 7   delete this.tmpObj; 8   this.y=y; 9 }

Rows 5th, 6, and 7: create a temporary attribute tmpobj to reference constructor A, execute it within B, and delete it after execution. When this. after x = x (here this is the object of B), B certainly has the X attribute. Of course, the X attribute of B is independent of the X attribute of, therefore, it cannot be regarded as a strict inheritance. Rows 5th, 6, and 7 have a simpler implementation, that is, using the call (apply) method: A. Call (this, X );

Both methods pass this to the execution of a. This points to the object of B, which is why a (x) is not directly used. This Inheritance Method is class inheritance (JS does not have a class. Here it only refers to the constructor). Although it inherits all the attribute methods of a constructor object, it cannot inherit the members of a's prototype object. To achieve this goal, we need to add prototype inheritance on this basis.

Through the example below, we can have a deep understanding of the prototype and the perfect inheritance of prototype participation in implementation.

 1 function A(x){  2   this.x = x;  3 }  4 A.prototype.a = "a";  5 function B(x,y){  6   this.y = y;  7   A.call(this,x);  8 }  9 B.prototype.b1 = function(){ 10 alert("b1"); 11 } 12 B.prototype = new A(); 13 B.prototype.b2 = function(){ 14   alert("b2"); 15 } 16 B.prototype.constructor = B; 17 var obj = new B(1,3);

In this example, B inherits. 7th row class inheritance: A. Call (this. X); As mentioned above. The prototype inherits 12th rows: B. Prototype = new ();

That is to say, the prototype of B points to one instance object of A. This instance object has the X attribute, undefined, and a attribute, and the value is "". Therefore, prototype B also has these two attributes (or, B and A establish a prototype chain, and B is the lower level of ). Because only the class inherits, B's instance object also has the X attribute, that is, the OBJ object has two X attributes with the same name. In this case, the prototype property X must be located in the Instance Object Property X, so obj. X is 1, not undefined. Line 2 defines the prototype B2, so the prototype B also has B2. Although 9th ~ Line 11 sets the original type method B1, but you will find that after line 1 is executed, prototype B no longer has the B1 method, that is, obj. B1 is undefined. Because row 12th changes the orientation of the B prototype, the original prototype object with B1 is discarded, and naturally there is no B1.

After the execution of row 12th is complete, the prototype B (B. prototype) points to the Instance Object of A, and the constructor of instance object of A is constructor A, so B. prototype. constructor is to construct object A (in other words, a constructs the prototype of object B ).

Alert (B. Prototype. constructor) is "function a (x ){...}". Similarly, obj. constructor is also a constructor, alert (obj. constructor) is "function a (x ){...} ", that is, B. prototype. constructor = obj. constructor (true), but B. prototype = obj. constructor. prototype (false), because the former is the prototype of B and has members: X, A, B2. The latter is the prototype of a and has members:. How can we fix this problem? In row 16th, the constructor of prototype B points to the constructor of type B again, then B. prototype = obj. constructor. prototype (true) has the following members: X, A, and B2.

If there are no 16th rows, Will OBJ = new B () call the constructor for instantiation? The answer is no. You will find that obj. Y = 3, so it is still instantiated by calling the B constructor. Although obj. constructor = a (true), but for the new B () behavior, the above three steps to create an instance object through the constructor are executed, step 1, create an empty object. Step 2: obj. _ PROTO _ = B. prototype, B. prototype is composed of X, A, and B2, obj. constructor points to B. prototype. constructor, that is, constructor A; step 3, call constructor B to set and initialize members, with properties X and Y. Although not adding 16 rows does not affect the properties of OBJ, as mentioned above, obj. constructor and obj. constructor. Prototype are affected. Therefore, after prototype inheritance is used, you need to modify the operation.

With regard to rows 12th and 16, in general, rows 12th make prototype B inherit all members of a's prototype object, however, the prototype of the constructor of the Instance Object of B also points to the prototype of a. Therefore, this defect should be corrected through row 3.

 

 

 

 

 

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.