Home Web Front-end JS Tutorial JS prototype and inheritance that front-end development must know_js object-oriented

JS prototype and inheritance that front-end development must know_js object-oriented

May 16, 2016 pm 06:23 PM
prototype inherit

1. Prototype and constructor

All JS functions have a prototype attribute, which refers to an object, the prototype object, also referred to as the prototype. This function includes constructors and ordinary functions. We are talking more about the prototype of the constructor, but we cannot deny that ordinary functions also have prototypes. For example, an ordinary function:
Copy code The code is as follows:

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


 Constructor, that is, constructing an object. First, let’s understand the process of instantiating an object through the constructor.
Copy code The code is as follows:

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


There are three steps to instantiate the obj object:

1. Create the obj object: obj=new Object();

 2. Point the internal __proto__ of obj to the prototype of the function A that constructs it. At the same time, obj.constructor===A.prototype.constructor (This is always true, even if A.prototype no longer points to the original A prototype, that is to say: the constructor property of the instance object of the class always points to the prototype.constructor of the "constructor"), thus making obj.constructor.prototype point to A.prototype (obj.constructor.prototype===A.prototype, this is not true when A.prototype changes, as will be encountered below). obj.constructor.prototype and the internal _proto_ are two different things. _proto_ is used when instantiating an object. obj does not have a prototype attribute, but it has an internal __proto__. You can use __proto__ to obtain the prototype attributes on the prototype chain. and prototype methods, FireFox exposes __proto__, which can be alerted in FireFox (obj.__proto__);

 3. Use obj as this to call constructor A to set members (i.e. object properties and object methods) and initialized.

When these three steps are completed, the obj object has no connection with the constructor A. At this time, even if the constructor A adds any members, it will no longer affect the instantiated obj object. At this time, the obj object has the x attribute and all members of the prototype object of constructor A. Of course, the prototype object has no members at this time.

The prototype object is initially empty, that is, it does not have a member (ie prototype properties and prototype methods). You can verify how many members a prototype object has by using the following method.
Copy code The code is as follows:

var num=0;
for(o in A.prototype) {
alert(o);//alert outputs the prototype attribute name
num ;
}
alert("member: " num);//alert outputs the number of all members of the prototype .


However, once prototype properties or prototype methods are defined, all objects instantiated through the constructor inherit these prototype properties and prototype methods, which is done internally The _proto_ chain is implemented.

For example:

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

Then all A objects have a say method, this The say method of the prototype object is the only copy shared by everyone, rather than every object having a copy of the say method.

2. Prototype and inheritance

First, let’s look at a simple inheritance implementation.
Copy code The code is as follows:

function A(x){
 this.x =x;
}
function B(x,y){
 this.tmpObj=A;
 this.tmpObj(x);
 delete this.tmpObj;
 this. y=y;
}


Lines 5, 6, and 7: Create a temporary attribute tmpObj to reference constructor A, then execute it inside B, and delete it after execution. When this.x=x is executed inside B (this here is the object of B), B will of course have the x attribute. Of course, the x attribute of B and the x attribute of A are independent, so they are not strictly inheritance. Lines 5, 6, and 7 have a simpler implementation, which is through 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 used directly. This inheritance method is class inheritance (js does not have classes, here it only refers to constructors). Although it inherits all the attribute methods of A's constructed object, it cannot inherit the members of A's prototype object. To achieve this goal, we need to add prototypal inheritance on this basis.


Through the following examples, you can have a deep understanding of prototypes and the perfect inheritance that prototypes participate in. (The core of this article is here^_^)
Copy code The code is as follows:

function A( x){
 this.x = x;
}
A.prototype.a = "a";
function B(x,y){
 this.y = y;
A.call(this,x);
}
B.prototype.b1 = function(){
alert("b1");
}
B.prototype = new A();
B.prototype.b2 = function(){
 alert("b2");
}
B.prototype.constructor = B;
var obj = new B (1,3);

This example is about B inheriting A. Line 7 class inheritance: A.call(this.x); As mentioned above. Prototypal inheritance is implemented in line 12: B.prototype = new A();

That means that the prototype of B points to an instance object of A. This instance object has the x attribute, which is undefined. Has an attribute with a value of "a". So the B prototype also has these two attributes (or in other words, B and A have established a prototype chain, and B is a subordinate of A). Because of the class inheritance just now, the instance object of B also has the x attribute, which means that the obj object has two x attributes with the same name. At this time, the prototype attribute x has to give way to the instance object attribute x, so obj.x is 1 , rather than undefined. Line 13 also defines the prototype method b2, so the B prototype also has b2. Although the prototype method b1 is set in lines 9 to 11, you will find that after the execution of line 12, the B prototype no longer has the b1 method, that is, obj.b1 is undefined. Because line 12 changes the B prototype pointer, the original prototype object with b1 is abandoned, and naturally there is no b1.

After line 12 is executed, B prototype (B.prototype) points to the instance object of A, and the constructor of the instance object of A is constructor A, so B.prototype.constructor is the constructor object A. (In other words, A constructs the prototype of B).

alert(B.prototype.constructor) comes out as "function A(x){...}". Similarly, obj.constructor is also an A constructor object. After alert(obj.constructor) comes out, it is "function A(x){...}", that is to say, 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, and the latter is the prototype of A and has members: a. How to fix this problem? On line 16, redirect the constructor of B prototype to the B constructor, then B.prototype===obj.constructor.prototype(true), all have members: x, a, b2 .

If there is no line 16, will obj = new B(1,3) call the A constructor for instantiation? The answer is no, you will find that obj.y=3, so it is still instantiated by the called B constructor. Although obj.constructor===A(true), for the behavior of new B(), the three steps mentioned above to create an instance object through the constructor are performed. The first step is to create an empty object; the second step is to create an empty object. Step, obj.__proto__ === B.prototype, B.prototype has x, a, b2 members, obj.constructor points to B.prototype.constructor, that is, constructor A; the third step, called constructor B To set and initialize members, have attributes x, y. Although not adding 16 lines does not affect the properties of obj, as mentioned in the previous paragraph, it does affect obj.constructor and obj.constructor.prototype. Therefore, after using prototypal inheritance, correction operations must be performed.

Regarding lines 12 and 16, in short, line 12 makes the prototype of B inherit all members of the prototype object of A, but also makes the prototype of the constructor of the instance object of B point to the prototype of A. So this flaw needs to be corrected through line 16.

Finished.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Packaging technology and application in PHP Packaging technology and application in PHP Oct 12, 2023 pm 01:43 PM

Encapsulation technology and application encapsulation in PHP is an important concept in object-oriented programming. It refers to encapsulating data and operations on data together in order to provide a unified access interface to external programs. In PHP, encapsulation can be achieved through access control modifiers and class definitions. This article will introduce encapsulation technology in PHP and its application scenarios, and provide some specific code examples. 1. Encapsulated access control modifiers In PHP, encapsulation is mainly achieved through access control modifiers. PHP provides three access control modifiers,

Introduction to the new map of Genshin Impact version 4.4 Introduction to the new map of Genshin Impact version 4.4 Jan 31, 2024 pm 06:36 PM

Introducing the new map of Genshin Impact version 4.4. Friends, Genshin Impact 4.4 version also ushered in the Sea Lantern Festival in Liyue. At the same time, a new map area will be launched in version 4.4 called Shen Yu Valley. According to the information provided, Shen Yugu is actually part of Qiaoying Village, but players are more accustomed to calling it Shen Yugu. Now let me introduce the new map to you. Introduction to the new map of Genshin Impact version 4.4. Version 4.4 will open "Chenyu Valley·Shanggu", "Chenyu Valley·Nanling" and "Laixin Mountain" in the north of Liyue. Teleportation anchor points have been opened for travelers in "Chenyu Valley·Shanggu" . ※After completing the prologue of the Demon God Quest·Act 3: The Dragon and the Song of Freedom, the teleportation anchor point will be automatically unlocked. 2. Qiaoyingzhuang When the warm spring breeze once again caressed the mountains and fields of Chenyu, the fragrant

C++ function inheritance explained: When should inheritance not be used? C++ function inheritance explained: When should inheritance not be used? May 04, 2024 pm 12:18 PM

C++ function inheritance should not be used in the following situations: When a derived class requires a different implementation, a new function with a different implementation should be created. When a derived class does not require a function, it should be declared as an empty class or use private, unimplemented base class member functions to disable function inheritance. When functions do not require inheritance, other mechanisms (such as templates) should be used to achieve code reuse.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

What are prototypes and prototype chains What are prototypes and prototype chains Nov 09, 2023 pm 05:59 PM

Prototype, an object in js, is used to define the properties and methods of other objects. Each constructor has a prototype attribute. This attribute is a pointer pointing to a prototype object. When a new object is created, the new object will be The prototype attribute of its constructor inherits properties and methods. Prototype chain, when trying to access the properties of an object, js will first check whether the object has this property. If not, then js will turn to the prototype of the object. If the prototype object does not have this property, it will continue to look for the prototype of the prototype.

See all articles