Home Web Front-end JS Tutorial JS Pro-Detailed explanation of inheritance in object-oriented programming_javascript skills

JS Pro-Detailed explanation of inheritance in object-oriented programming_javascript skills

May 16, 2016 pm 05:34 PM
js inherit object-oriented

Prototype chaining:

Use prototypes to inherit properties and methods. Review the relationship between constructor, prototype and instance. Each constructor has a prototype attribute, which points to a prototype object; the prototype object also has a constructor attribute, which points to the function; and the instance also has an internal pointer (__proto__) pointing to the prototype object. What would happen if this prototype object was an instance of another object? In this way, the prototype object contains a pointer to another type. Correspondingly, the other prototype also contains a pointer to another constructor.

JS inheritance is very simple, that is, set the prototype of the subclass to an (instantiated) object of the parent class

Copy code The code is as follows:

function SuperType(){
this.property = true;
}

SuperType.prototype.getSuperValue = function(){
Return this.property;
};

function SubType(){
this.subproperty = false;
}

//inherit from SuperType
SubType .prototype = new SuperType();

SubType.prototype.getSubValue = function (){
return this.subproperty;
};

var instance = new SubType() ;
alert(instance.getSuperValue()); //true

Final result: instance's __proto__ points to the SubType.prototype object, and the __proto__ attribute of the SubType.prototype object And points to the SuperType.prototype object. getSuperValue() is a method, so it still exists in the prototype, and property is an instance property, so it now exists in the instance of SubType.prototype. instance.constructor now points to SuperType. This is because SubType.prototype points to SuperType.prototype, and the constructor property of SuperType.prototype points to the SuperType function, so instance.constructor points to SuperType.

By default, all reference types inherit from Object. This is because the prototype object of all functions is an instance of Object by default, so the internal prototype(__proto__) points to Object.Prototype.

Relationship between prototype and instance: You can use 2 methods to determine the relationship between prototype and instance.
- instancef operator: Use this operator to test the constructor that appears in the instance and prototype chain, and it will return true

Copy codeThe code is as follows:

alert(instance instanceof Object); //true
alert(instance instanceof SuperType); //true
alert(instance instanceof SubType); / /true

- isPrototypeOf() method: As long as it is a prototype that appears in the prototype chain, it can be said to be the prototype of the instance derived from the prototype chain.
Copy code The code is as follows:

alert(Object.prototype.isPrototypeOf(instance)); //true
alert(SuperType.prototype.isPrototypeOf(instance)); //true
alert(SubType.prototype.isPrototypeOf(instance)); //true

given Note on adding methods to a class: Sometimes we add methods to subclasses, or override some methods of the parent class. At this time, it should be noted that these methods must be defined after inheritance. In the following example, after SubType inherits SuperType, we add a new method getSubValue() to it and rewrite the getSuperValue() method. For the latter, only SubType instances will use the overridden method, and SuperType instances will still use the original getSuperValue() method.
Copy code The code is as follows:

function SuperType(){
 this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
//inherit from SuperType
SubType.prototype = new SuperType();
//new method
SubType.prototype.getSubValue = function (){
 return this. subproperty;
};
//override existing method
SubType.prototype.getSuperValue = function (){
 return false;
};
var instance = new SubType();
alert(instance.getSuperValue()); //false

Another thing to note is that when implementing inheritance through the prototype chain, you cannot use object literals to create prototype methods, because this will overwrite the prototype chain. As shown in the code below, after SubType inherits SuperType, it uses object literals to add methods to the prototype. However, doing so will rewrite the SubType prototype. The rewritten SubType.prototype contains an instance of Object, thus cutting off the connection with SuperType relationship.
Copy code The code is as follows:

function SuperType(){
 this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
//inherit from SuperType
SubType.prototype = new SuperType();
//try to add new methods - this nullifies the previous line
SubType.prototype = {
getSubValue: function (){
  return this.subproperty;
 },
someOtherMethod: function (){
return false;
}
};
var instance = new SubType();
alert(instance.getSuperValue()); //error!

Prototype chain problem: Same as prototype, when using reference type value Sometimes, there will be problems with the prototype chain. Recall from the previous content that a prototype property containing a reference type value will be shared by all instances, which is why we define the reference type value in the constructor rather than in the prototype. When inheritance is implemented through the prototype chain, the prototype will actually become an instance of another type, so the original instance properties will smoothly become the current prototype properties.
Copy code The code is as follows:

function SuperType(){
 this.colors = ["red", "blue", "green"];
}
function SubType(){
}
//inherit from SuperType
SubType.prototype = new SuperType();
var instance1 = new SubType();
instance1.colors.push(“black”);
alert(instance1.colors); //”red,blue,green,black”
var instance2 = new SubType();
alert(instance2.colors); //"red,blue,green,black"

In the SuperType constructor, we define a colors array, Each SuperType instance will have its own colors array. But when SubType uses the prototype chain to inherit SuperType, SubType.prototype becomes an instance of SuperType, so it has its own colors attribute, that is, SubType.prototype.colors attribute. Therefore, when creating a SubType instance, all instances share this property. As shown in the code above.

The second problem is: when creating an instance of a subclass, parameters cannot be passed to the constructor of the superclass. In fact, it should be said that there is no way to pass parameters to the constructor of a superclass without affecting all object instances. Because of these issues, we will not use the prototype chain alone.

-------------------------------------------------- ----------------------------------

Constructor stealing:
To solve the above problem, developers invented a technique called constructor stealing. The idea behind this technique is to call the supertype constructor inside the subtype constructor. (A function is nothing but an object that executes code in a specific environment?) We can execute a constructor on a newly created object by using the apply() or call() method.

Copy code The code is as follows:

function SuperType(){
 this.colors = ["red", "blue", "green"];
}
function SubType(){
 //inherit from SuperType
 SuperType.call(this);
}
var instance1 = new SubType();
instance1.colors.push(“black”);
alert(instance1.colors); //”red,blue,green,black”
var instance2 = new SubType();
alert(instance2.colors); //"red, blue, green"

We use the call() method in SubType to call the SuperType constructor. In fact It is to execute all the object initialization code defined in the SuperType() function on the new SubType object. The result is that each SubType instance has its own copy of the colors property.

Passing parameters: A big benefit of using the borrowed constructor method is that we can pass parameters from the constructor of the subclass to the constructor of the parent class.

Copy code The code is as follows:

function SuperType(name){
 this.name = name;
}
function SubType(){
 //inherit from SuperType passing in an argument
 SuperType. call(this, “Nicholas”);
 //instance property
 this.age = 29;
}
var instance = new SubType();
alert(instance.name); //"Nicholas";
alert(instance.age); //29

The new SuperType constructor adds a new parameter name. We pass it to SuperType while calling SuperType Parameter "Nicholas". In order to prevent the supertype constructor from overwriting the properties of the subtype, you can define the properties of the subclass after calling the supertype constructor.

Problems with borrowing constructors: Methods are all defined in the constructor and cannot be reused. Moreover, methods defined in the supertype's prototype are not visible to subtypes. As a result all types can only use the constructor pattern.

-------------------------------------------------- ----------------------------------

Combined inheritance:
An inheritance pattern that combines the advantages of prototype chains and borrowed constructors. Use the prototype chain to inherit prototype properties and methods, and use borrowed constructors to inherit instance properties. As in the following example, we use the call() method to call the constructor of SuperType (each SubType instance has its own name and colors attributes, as well as the age attribute of SubType); then assign the SuperType instance to the SubType prototype to make it inherit. SuperType's sayName() method (this method is shared by each instance).

Copy code The code is as follows:

function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}

SuperType.prototype.sayName = function(){
alert(this.name);
};

function SubType(name, age){
//inherit properties
SuperType.call(this, name);
this.age = age;
}
//inherit methods
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function(){
alert(this.age);
};

var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black "
instance1.sayName(); //"Nicholas";
instance1.sayAge(); //29
var instance2 = new SubType("Greg", 27);
alert(instance2 .colors); //"red,blue,green"
instance2.sayName(); //"Greg";
instance2.sayAge(); //27


Prototypal Inheritance:
Copy code The code is as follows:

function object(o){
 function F(){}
 F.prototype = o;
 return new F();
}
--------- -------------------------------------------------- --------------------------


Parasitic Inheritance:

Same disadvantages as constructor

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 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.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

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.

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles