


JS Pro-Detailed explanation of inheritance in object-oriented programming_javascript skills
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
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
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.
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.
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.
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.
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.
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.
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).
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:
function object(o){
function F(){}
F.prototype = o;
return new F();
}
--------- -------------------------------------------------- --------------------------
Parasitic Inheritance:
Same disadvantages as constructor

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.