


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!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
