Four ways of inheritance in javascript (code examples)
This article brings you the four methods (code examples) of JavaScript inheritance. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Prototype chain inheritance
Core: Use the instance of the parent class as the prototype of the subclass
Disadvantages: New prototype method for the parent class/ Prototype attributes can be accessed by subclasses. Once the parent class changes, everything else changes
function Person (name) { this.name = name; }; Person.prototype.getName = function () { //对原型进行扩展 return this.name; }; function Parent (age) { this.age = age; }; Parent.prototype = new Person('老明'); //这一句是关键 //通过构造器函数创建出一个新对象,把老对象的东西都拿过来。 Parent.prototype.getAge = function () { return this.age; }; // Parent.prototype.getName = function () { //可以重写从父类继承来的方法,会优先调用自己的。 // console.log(222); // }; var result = new Parent(22); console.log(result.getName()); //老明 //调用了从Person原型中继承来的方法(继承到了当前对象的原型中) console.log(result.getAge()); //22 //调用了从Parent原型中扩展来的方法
2. Constructive inheritance
Basic idea
Borrow constructor The basic idea is to use call
or apply
to copy (borrow) the properties and methods specified by this
in the parent class to the instance created by the subclass.
Because this
object is bound at runtime based on the execution environment of the function. That is, globally, this
is equal to window
, and when a function is called as a method of an object, this
is equal to that object. The call
, apply
methods can change the object context of a function from the initial context to the new object specified by thisObj.
So, this borrowed constructor is, when new
the object (when new is created, this
points to the created instance), a new instance is created Object,
and execute the code inside Parent
, and Parent
uses call
to call Person
, that is to say, this
points to a new instance,
so the this
related properties and methods in Person
will be assigned to the new instance, and Instead of assigning the value to Person
,
so all instances have these this
attributes and methods defined by the parent class.
Because the properties are bound to this
, they are assigned to the corresponding instances when called, and the values of each instance will not affect each other.
Core: Using the constructor of the parent class to enhance the instance of the subclass is equivalent to copying the instance attributes of the parent class to the subclass (no prototype is used)
Disadvantages: Methods are all in the constructor As defined in, only instance properties and methods of the parent class can be inherited, prototype properties/methods cannot be inherited, and function reuse cannot be achieved. Each subclass has a copy of the parent class instance function, which affects performance
function Person (name) { this.name = name; this.friends = ['小李','小红']; this.getName = function () { return this.name; } }; // Person.prototype.geSex = function () { //对原型进行扩展的方法就无法复用了 // console.log("男"); // }; function Parent = (age) { Person.call(this,'老明'); //这一句是核心关键 //这样就会在新parent对象上执行Person构造函数中定义的所有对象初始化代码, // 结果parent的每个实例都会具有自己的friends属性的副本 this.age = age; }; var result = new Parent(23); console.log(result.name); //老明 console.log(result.friends); //["小李", "小红"] console.log(result.getName()); //老明 console.log(result.age); //23 console.log(result.getSex()); //这个会报错,调用不到父原型上面扩展的方法
3. Combined inheritance
Combined inheritance (all instances can have their own properties and can use the same method. Combined inheritance avoids the defects of the prototype chain and borrowed constructors, and combines the two The advantage of each is the most commonly used inheritance method)
Core: By calling the parent class constructor, inherit the properties of the parent class and retain the advantages of passing parameters, and then use the parent class instance as the prototype of the subclass to achieve Function reuse
Disadvantages: The parent class constructor is called twice and two instances are generated (the subclass instance blocks the one on the subclass prototype)
function Person (name) { this.name = name; this.friends = ['小李','小红']; }; Person.prototype.getName = function () { return this.name; }; function Parent (age) { Person.call(this,'老明'); //这一步很关键 this.age = age; }; Parent.prototype = new Person('老明'); //这一步也很关键 var result = new Parent(24); console.log(result.name); //老明 result.friends.push("小智"); // console.log(result.friends); //['小李','小红','小智'] console.log(result.getName()); //老明 console.log(result.age); //24 var result1 = new Parent(25); //通过借用构造函数都有自己的属性,通过原型享用公共的方法 console.log(result1.name); //老明 console.log(result1.friends); //['小李','小红']
4. Parasitic combination inheritance
Core: Through parasitism, the instance attributes of the parent class are cut off, so that when the constructor of the parent class is called twice, the instance method will not be initialized twice/ Attributes avoid the shortcomings of combined inheritance
Disadvantages: It is perfect, but the implementation is more complicated
function Person(name) { this.name = name; this.friends = ['小李','小红']; } Person.prototype.getName = function () { return this.name; }; function Parent(age) { Person.call(this,"老明"); this.age = age; } (function () { var Super = function () {}; // 创建一个没有实例方法的类 Super.prototype = Person.prototype; Parent.prototype = new Super(); //将实例作为子类的原型 })(); var result = new Parent(23); console.log(result.name); console.log(result.friends); console.log(result.getName()); console.log(result.age);
[Related recommendations: JavaScript video tutorial]
The above is the detailed content of Four ways of inheritance in javascript (code examples). 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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



Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

Principle analysis and practical exploration of the Struts framework. As a commonly used MVC framework in JavaWeb development, the Struts framework has good design patterns and scalability and is widely used in enterprise-level application development. This article will analyze the principles of the Struts framework and explore it with actual code examples to help readers better understand and apply the framework. 1. Analysis of the principles of the Struts framework 1. MVC architecture The Struts framework is based on MVC (Model-View-Con

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

The RPM (RedHatPackageManager) tool in Linux systems is a powerful tool for installing, upgrading, uninstalling and managing system software packages. It is a commonly used software package management tool in RedHatLinux systems and is also used by many other Linux distributions. The role of the RPM tool is very important. It allows system administrators and users to easily manage software packages on the system. Through RPM, users can easily install new software packages and upgrade existing software

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

The chage command in the Linux system is a command used to modify the password expiration date of a user account. It can also be used to modify the longest and shortest usable date of the account. This command plays a very important role in managing user account security. It can effectively control the usage period of user passwords and enhance system security. How to use the chage command: The basic syntax of the chage command is: chage [option] user name. For example, to modify the password expiration date of user "testuser", you can use the following command

The basic principles and implementation methods of Golang inheritance methods In Golang, inheritance is one of the important features of object-oriented programming. Through inheritance, we can use the properties and methods of the parent class to achieve code reuse and extensibility. This article will introduce the basic principles and implementation methods of Golang inheritance methods, and provide specific code examples. The basic principle of inheritance methods In Golang, inheritance is implemented by embedding structures. When a structure is embedded in another structure, the embedded structure has embedded

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,
