


Detailed explanation of javascript inheritance mechanism examples_javascript skills
The examples in this article describe the JavaScript inheritance mechanism. Share it with everyone for your reference. The specific analysis is as follows:
It is generally difficult for beginners to understand the inheritance mechanism of Javascript language. There is no concept of "subclass" and "parent class", and there is no distinction between "class" and "instance". It all relies on one A very peculiar "prototype chain" model to implement inheritance.
I spent a lot of time studying this part and took a lot of notes. But they are all forced memories and cannot be understood fundamentally.
1. How to create a class
Suppose there is a class called Person as follows:
This.name = name;
This.age = age;
}
Person.prototype.getName = function() {
Return this.name;
}
As above: Person represents all people on the earth, and everyone has these two basic attributes: name and age; now we have to implement a student class, and then we know; a student is also a person, and students also have attributes such as name and age. ;The question now is how to establish this relationship?
Let’s first take a look at how a pure object-oriented language does it (such as: Actionscrpt3)
2. How to do it by switching to js
Before explaining the implementation of the inheritance mechanism of js, let’s first understand the prototype chain of js:
person.getName(); // "Poised-flw"
As for the getName() method above, how is it executed? First, I will look for the getName() method in the Person function and find that there is not; then I will go to Person.prototype to search and find that there is! Then call it, what if not? Continue searching along the prototype in the same way until you find a method or reach the top of the prototype chain!
For example, there is now a constructor called DOG, which represents the prototype of the dog object.
this.name = name;
}
Using new on this constructor will generate an instance of the dog object.
alert(dogA.name); // Da Mao
Pay attention to the this keyword in the constructor, which represents the newly created instance object.
3. Disadvantages of new operator
Using a constructor to generate instance objects has a disadvantage, that is, properties and methods cannot be shared.
For example, in the constructor of the DOG object, set the common attributes species of an instance object.
this.name = name;
this.species = 'Canidae';
}
Then, generate two instance objects:
var dogB = new DOG('二毛');
The species attributes of these two objects are independent, and modifying one will not affect the other.
alert(dogB.species); // Display "canine", not affected by dogA
Each instance object has its own copy of properties and methods. This not only fails to achieve data sharing, but is also a huge waste of resources.
So: The idea of inheritance: Implement the inheritance mechanism through the unique prototype chain of js!
4. Inheritance based on prototype chain
1. Direct inheritance implementation
Person.call(this, name, age);
This.sid = sid;
}
Students.prototype = new Person(); //Put Person on the prototype chain of Students to implement the inheritance mechanism
Students.prototype.constructor = Students;
Students.prototype.getResults = function() {
// Get student scores
}
Be sure not to miss the line Students.prototype.constructor = Students! , when defining a constructor, its default prototype is an Object instance, and then the constructor property of the prototype is automatically set to the function itself! ! ! If the prototype is manually set to another object, the new object will naturally not have the constructor value of the original object, so its constructor property needs to be reset. Such as:
This.time = "now";
}
console.log(Test.prototype); // Object {} an empty object
console.log(Test.prototype.constructor); // function() {this.time = "now";}, and the function itself
// If you manually change the prototype attribute of Test
Test.prototype = {
SomeFunc: function() {
console.log('hello world!');
}
};
console.log(Test.prototype.constructor); // function Object() { [native code] }
// Then you will find that you pointed it completely wrong, so when you manually change the prototype attribute, you need to change its constructor pointer;
After the above test, you will know why the constructor value needs to be modified.
2. Encapsulate inherited functions extend
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
}
In fact, the function of this function is just an encapsulation of the above inheritance process. The differences are:
It only inherits the prototype attribute of superClass and does not inherit the attributes in the superClass constructor;
The advantage of this is that it reduces the cost of creating a new constructor!
Of course, the subsequent problem is that subClass cannot inherit all attributes of superClass through this function alone
Improvements:
Person.call(this, name, age);
5. Summary
Using the prototype chain principle of js, we can easily implement the inheritance mechanism of js. Although it is not very strict, my goal has been achieved: repeated code should appear once as much as possible!
I hope this article will be helpful to everyone’s JavaScript programming design.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

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.

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.

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.

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.

Title: An in-depth exploration of the storage location and mechanism of Golang variables. As the application of Go language (Golang) gradually increases in the fields of cloud computing, big data and artificial intelligence, it is particularly important to have an in-depth understanding of the storage location and mechanism of Golang variables. In this article, we will discuss in detail the memory allocation, storage location and related mechanisms of variables in Golang. Through specific code examples, it helps readers better understand how Golang variables are stored and managed in memory. 1.Memory of Golang variables

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

CSS reflow and repaint are very important concepts in web page performance optimization. When developing web pages, understanding how these two concepts work can help us improve the response speed and user experience of the web page. This article will delve into the mechanics of CSS reflow and repaint, and provide specific code examples. 1. What is CSS reflow? When the visibility, size or position of elements in the DOM structure changes, the browser needs to recalculate and apply CSS styles and then re-layout

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more
