A detailed explanation of the inheritance mechanism in js
Preface
I have been learning vue recently, and I finally have time to write something on the weekend (I am a little excited when I think about being able to deceive likes again!). In the basics of JavaScript, in addition to closures, inheritance is also a difficulty. Because of the length of the article, I plan to divide it into two parts. Also based on "Javascript Advanced Programming", I will give a detailed explanation. If there is anything wrong, please correct me.
Preparatory knowledge
In order to better explain inheritance, let’s put some preparatory knowledge first.
1. Constructor, instance
Constructor is a function used to create objects, and is essentially a function. The difference from other functions is that the calling method is different:
If it is called through the
new
operator, it is the constructorIf it is not called through the
new
operator, it is an ordinary function
Example:
function Person(name, age) { this.name = name; this.age = age; } //当做构造函数调用 var person1 = new Person('Mike',10); //当做普通函数调用,这里相当于给window对象添加了name和age属性,这个不是重点,只要注意调用方式 Person('Bob',12); console.log(person1)//Person {name: "Mike", age: 10} console.log(name)//Bob console.log(age)//12
in var person1 = new Person('Mike',10);
, the function Person
is called through the new operator, and person1
is generated. The Person here is Called the
constructor , person1 is called a
instance of the
Person function object. There will be a constructor attribute in the instance, pointing to the corresponding constructor
, see the following example:
function Person(name, age) { this.name = name; this.age = age; } var person1 = new Person('Mike',10); var person2 = new Person('Alice',20); console.log(person1.constructor)//function Person(){省略内容...} console.log(person2.constructor)//function Person(){省略内容...}
prototype attribute, which is a
pointer that points to its prototype object. The essence of the prototype object is also an object. This sentence may be a bit difficult to understand when you first read it. For example, take the function just now:
function Person(name, age) { this.name = name; this.age = age; } console.log(Person.prototype)//object{constructor:Person}
Person.prototype points to an object, which is the prototype of
Person Object , and this object has a constructor attribute, which points to the
Person function object. Feeling a little dizzy? It doesn't matter, next we will use a better method than giving examples-drawing pictures.
From the picture we can see:
- The
prototype
of the function object points to the prototype object, and the
constructorof the prototype object points to the
of the instance object of the function object The [Protoptype]
attribute points to the
prototype object . The [Protoptype]here is the
internal property . It can be understood that it exists, but it is not allowed. When we access (although some browsers allow access to this attribute, let's understand it this way first), the function of this attribute is: Allow the instance to access the properties and methods in the prototype object through this attribute. For example:
function Person(name, age) { this.name = name; this.age = age; } //在原型对象中添加属性或者方法 Person.prototype.sex = '男'; var person1 = new Person('Mike',10); var person2 = new Person('Alice',20); //只给person2设置性别 person2.sex = '女'; console.log(person1.sex)//'男' console.log(person2.sex)//'女'
sex attribute for the
person1 instance, but because of
[Protoptype] exists, the corresponding attribute in the prototype object will be accessed;
At the same time, after we set the
sex attribute to person2, the output is 'female', indicating that only when the
instance itself does not have the corresponding attribute or method Only then will we find the corresponding properties or methods on the prototype object
The principle of the prototype chain is to let one reference type inherit the properties and methods of another reference type. Let’s review the knowledge just mentioned:
Prototype object points to the constructor through the
constructor
attributeInstancePoints to the prototype object through the
[Prototype]
attribute
What happens if the prototype object is equal to an instance of another constructor? For example:
function A() { } //在A的原型上绑定sayA()方法 A.prototype.sayA = function(){ console.log("from A") } function B(){ } //让B的原型对象指向A的一个实例 B.prototype = new A(); //在B的原型上绑定sayB()方法 B.prototype.sayB = function(){ console.log("from B") } //生成一个B的实例 var a1 = new A(); var b1 = new B(); //b1可以调用sayB和sayA b1.sayB();//'from B' b1.sayA();//'from A'
Now look at the code combined with the picture:
- First, we created two function objects A and B,
and also generated their prototype objects
Next, we added the
sayA()
method
* to the prototype object of A, and then the critical stepB.prototype = new A() ;
, we let theprotytype
pointer of function object B point to an instance of A, please pay attention to my description: let theof function object B The protytype
pointer points to an instance of A, which is why in the end, B's prototype object no longer has a constructor attribute. In fact, B originally had a real prototype object, which could have been passed B.prototype access, but we have now rewritten this pointer so that it points to another object, so the real prototype object of B cannot be accessed now. Instead, the new prototype object is an instance of A, so naturally there is noconstructor
AttributeNext we add a sayB method# to the object pointed to by
B.prototype
- ##Then, we generated an instance b1
- Finally, we called the sayB method of b1, which can be executed. Why?
Because b1 has a [Prototype]property that can access the methods in B prototype;
- We called the sayA method of b1, Can be executed, why?
Because b1 can access B prototype along the [Prototype]property, B prototype continues to access A prototype along the
[Prototype]property, and finally on A.prototype The sayA() method is found, so it can be executed
b1 inherits the properties and methods of A, this A structure that [Prototype] continuously connects instances and prototype objects is the prototype chain. It is also the main implementation method of inheritance in js.
Original text from https://segmentfault.com/a/1190000007376061
The above is the detailed content of A detailed explanation of the inheritance mechanism in js. For more information, please follow other related articles on the PHP Chinese website!

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.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

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.

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

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

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

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.
