


What are the inheritance methods in js? Introduction to two methods of js inheritance (with code)
The inheritance of js is different from the traditional inheritance of java. js is inheritance based on the prototype chain. JavaScript inheritance can be divided into two categories: object-based inheritance and type-based inheritance. Let’s take a closer look at js inheritance.
JS object-based inheritance
Object-based inheritance is also called prototypal inheritance. We know that objects created through JavaScript literals will be connected to Object.prototype, so we use Object.prototype to implement inheritance. Essentially, the class is abandoned and the constructor is not called. Instead, Object.create() is used to directly let the new object inherit the properties of the old object. For example:
var person = { name: "Jack", getName: function () { return this.name; } } var p1 = Object.create(person); console.log(p1.getName()); //Jack
The code is very simple, person has one attribute and one method. Object p1 is inherited through Object.create(). The first parameter prototype points to the prototype of person, so object p1 inherits the attributes and methods of person.
Object.create() can also specify a second parameter, the data attribute, to add it to the new object. The data attribute can be set to 4 descriptor values, writable, enumerable, and configurable. The meaning of the last three can be guessed by looking at the names. If not specified, the default is false. Since it has little to do with this article, I won’t digress. Just look at setting the value:
var p2 = Object.create(person, { name: { value: "Zhang" } }); console.log(p2.getName()); //Zhang
Using Object.create() is equivalent to creating a brand new object. You can add any new value to the object. Increase and overload its properties and methods:
var person = { name: "Jack", getName: function () { return this.name; }, getAge: function() { return this.age; } //注意并没有age这个成员变量,依赖子类实现 } var p3 = Object.create(person); p3.name = 'Rose'; p3.age = 17; p3.location = '上海'; p3.getLocation = function() { return this.location; } console.log(p3.getName()); //Rose console.log(p3.getAge()); //17 console.log(p3.getLocation()); //上海
There is no age property in person, so you will get undefined when you call person.getAge();. But the age attribute is newly defined in object p3, so the getAge method of the base class can be called correctly. In addition, the subclass overloads the value of name, and newly defines the location attribute and getLocation method. The results are shown above and will not be described again.
Inheritance based on js classes
Type-based inheritance is inheritance that depends on the prototype through the constructor, rather than relying on the object. For example:
function Person(name) { this.name = name; this.getName = function () { return this.name; }; } function Student(name, age) { Person.call(this, name); this.age = age; this.getAge = function () { return this.age; }; } Student.prototype = new Person(); //需要通过new来访问基类的构造函数 var p = new Person('Cathy'); var s = new Student('Bill', 23); console.log(p.getName()); //Cathy console.log(s.getName()); //Bill console.log(s.getAge()); //23
Student inherits from Person. Although name is defined in the base class Person, after calling Person's constructor with new, this will be bound to the subclass Student object, so name is ultimately defined on the subclass Student object. The results are shown above and will not be described again.
Protecting Privacy
The reason why getName, getAge and other methods are defined is that we do not want users to directly access attributes such as name, age and so on. Unfortunately, neither of the above two inheritances can protect privacy, and they can directly access properties like p.name and p.age. If you think the privacy of these attributes is very important and want to simulate the effect of private attributes in OO language, you can use function modularization.
The so-called function modularization essentially means creating a new object within the function, using the properties of the parameter object in the method of the new object, and then returning the new object. At this time, the new object does not have the attributes of the parameter object, achieving the purpose of protecting privacy. The code is as follows:
var person = function(spec) { var that = {}; //新对象 that.getName = function () { return spec.name; }; //使用参数的属性 that.getAge = function() { return spec.age; }; //使用参数的属性 return that; //返回新对象 } var p4 = person({name: 'Jane', age: 20}); console.log(p4.name); //undefined console.log(p4.age); //undefined console.log(p4.getName()); //Jane console.log(p4.getAge()); //20
Because the function person returns the new object that, and there are no name and age attributes in that, direct access will result in undefined. Name and age can only be obtained through the two interfaces exposed by that.
It is also very convenient to further implement multi-layer inheritance. The effect is as follows, so I won’t go into details:
var student = function(spec) { var that = person(spec); //新对象继承自person that.getRole = function() { return 'student'; }; //新对象增加方法 that.getInfo = function() { return spec.name + ' ' + spec.age + ' ' + that.getRole(); }; return that; //返回新对象 }; var p5 = student({name:'Andy', age:12}); console.log(p5.name); //undefined console.log(p5.getName()); //Andy console.log(p5.getRole()); //student console.log(p5.getInfo()); //Andy 12 student
Recommended related articles:
JS inheritance--prototype chain inheritance and class inheritance_ Basic knowledge
Several ways to implement inheritance in JS
Inheritance and other inheritance in JavaScript_javascript skills
The above is the detailed content of What are the inheritance methods in js? Introduction to two methods of js inheritance (with code). 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











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

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
