JavaScript prototype and inheritance are a must for interviews
javascriptThe column introduces prototypes and inheritance that must be learned in interviews
##Related free learning recommendations:This article starts from the following aspectsjavascript( Video)
- 0How to understand object-oriented
- 1Create objects The way
- 2 Tips to remember the prototype chain
- 3instanceof simulation implementation
- 4new Keyword simulation implementation
- 5Inherited implementation (step by step implementation)
var o1 = {name: 'o1'} var o2 = new Object({name: 'o2'})
var M = function(name){ this.name = name } var o3 = new M('o3')
var o4 = Object.create(p)
Memory always There are rules. For example, when you learn trigonometric functions in high school, you need to memorize a lot of formulas. If you force yourself to memorize all the formulas, it will easily become confusing. However, if you memorize the core points, the rest of the formulas only require a little derivation. The same goes for the prototype chain. If you remember a few points at the beginning, you won't get confused later. Key concepts in the prototype chain:constructor, instance, constructor, __ proto__, prototype, first of all Remember their relationship
- The instance (object) has
- proto, the instance (object) does not have prototype The constructor has prototype, and prototype has is an object, then the prototype satisfies the above one. In addition to having
- proto, it also contains constructor . The constructor of the prototype's constructor points to the constructor itself, which is M.prototype in the above example. constructor === M
Please keep in mind the above three points, the complete inheritance summarized later is closely related to this
In factConstructor, Instance, constructor, __ proto__, prototype are already related in the above example and 3 points That’s it in the introduction. Let’s review again
- The constructor is an ordinary function, but there is the new keyword in front
- Through
new Add constructor , and the generated object is an instance.
- Take the o3 instance generated above as an example
o3.__proto__ === M.prototype //true o3.prototype //undefined o3.__proto__ === M.prototype //true
Copy after login - The o3 instance itself does not have a constructor, but it will be searched upward with the help of the prototype chain, that is,
o3.constructor === M.prototype.constructor // true o3.constructor === M //true
Copy after login
Summary After clarifying the relationship between these keywords, the prototype chain will become much clearer3 instanceof simulation implementation
# What is the principle of ##instanceof? Let’s first look at using
[] instanceof Array // true
. That is, the left side is the object and the right side is the type. instanceof is to determine whether the prototype of the right type is on the prototype chain of the left instance, as shown in the following example
[].__proto__ === Array.prototype //true Array.prototype.__proto__ === Object.prototype //true Object.prototype__proto__ //null
Then implement instanceof based on this idea, you will definitely be more impressed
new process happened What?4 new simulation implementation (brief version)function myInstanceof2(left, right){ if(left === null || left === undefined){ return false } if(right.prototype === left.__proto__) { return true } left = left.__proto__ return myInstanceof2(left, right) } console.log(myInstanceof2([], Array))Copy after login
- Generate an empty object
- The
- proto
of this empty object is assigned to the prototype of the constructor
Bind this to point to - Return this object
-
// 构造函数 function M(name){ this.name = name } // 原生new var obj = new M('123') // 模拟实现 function create() { // 生成空对象 let obj = {} // 拿到传进来参数的第一项,并改变参数类数组 let Con = [].shift.call(arguments) // 对空对象的原型指向赋值 obj.__proto__ = Con.prototype // 绑定this //(对应下面使用来说明:Con是参数第一项M, // arguments是参数['123'], // 就是 M方法执行,参数是'123',执行这个函数的this是obj) let result = Con.apply(obj, arguments) return result instanceof Object ? result : obj } var testObj = create(M, '123') console.log('testObj', testObj)
Copy after login5 Implementation of inheritance (step by step implementation)
- Construction method core Parent1.call(this)
-
// 构造方法方式 function Parent1(){ this.name = 'Parent1' } Parent1.prototype.say = function () { alert('say') } function Child1(){ Parent1.call(this) this.type = 'type' } var c1 = new Child1() c1.say() //报错
Copy after login
Thinking: Why does call implement inheritance? What is the essence of call?
- Only inherit the core through prototype Child2.prototype = new Parent2()
-
// 原型 function Parent2(){ this.name = 'Parent2' this.arr = [1,2] } Parent2.prototype.say = function () { alert('say') } function Child2(){ // Parent2.call(this) this.type = 'type' } Child2.prototype = new Parent2() var c21 = new Child2() var c22 = new Child2() c21.say() c21.arr.push('9') console.log('c21.arr : ', c21.arr) console.log('c22.arr : ', c22.arr)
Copy after login
Thinking: Why is it written like this to be the same reference?
Combined inheritance 1
Thinking: Is there no problem if I write like this?function Parent3(){ this.name = 'Parent3' this.arr = [1,2] } Parent3.prototype.say = function () { alert('say') } function Child3(){ Parent3.call(this) this.type = 'type' } Child3.prototype = new Parent3() var c31 = new Child3() var c32 = new Child3() c31.say() c31.arr.push('9') console.log('c31.arr : ', c31.arr) console.log('c31.arr : ', c32.arr)Copy after login
答 : 生成一个实例要执行 Parent3.call(this) , new Child3(),也就是Parent3执行了两遍。
- 组合继承2
改变上例子 的
Child3.prototype = new Parent3()
为
Child3.prototype = Parent3.prototype
缺点 : 很明显,无法定义子类构造函数原型私有的方法
-
组合继承优化3 再次改变上例子 的
Child3.prototype = Parent3.prototype
Copy after login
为
Child3.prototype = Object.create(Parent3.prototype)
问题就都解决了。 因为Object.create的原理是:生成一个对象,这个对象的proto, 指向所传的参数。
思考 :是否还有疏漏?一时想不起来的话,可以看下这几个结果
console.log(c31 instanceof Child3) // true console.log(c31 instanceof Parent3) // true console.log(c31.constructor === Child3) // false console.log(c31.constructor === Parent3) // true
所以回想起文章开头所说的那几个需要牢记的点,就需要重新赋值一下子类构造函数的constructor: Child3.prototype.constructor = Child3,完整版如下
function Parent3(){ this.name = 'Parent3' this.arr = [1,2] } Parent3.prototype.say = function () { alert('say') } function Child3(){ Parent3.call(this) this.type = 'type' } Child3.prototype = Object.create(Parent3.prototype) Child3.prototype.constructor = Child3 var c31 = new Child3() var c32 = new Child3() c31.say() c31.arr.push('9') console.log('c31.arr : ', c31.arr) console.log('c31.arr : ', c32.arr) console.log('c31 instanceof Child3 : ', c31 instanceof Child3) console.log('c31 instanceof Parent3 : ', c31 instanceof Parent3) console.log('c31.constructor === Child3 : ', c31.constructor === Child3) console.log('c31.constructor === Parent3 : ', c31.constructor === Parent3)
5 es6的继承
class Parent{ constructor(name) { this.name = name } getName(){ return this.name } } class Child{ constructor(age) { this.age = age } getAge(){ return this.age } }
es6继承记住几个注意事项吧
- 1 构造函数不能当普通函数一样执行 Parent() 是会报错的
- 2 不允许重定向原型 Child.prototype = Object.create(Parent.prototype) 无用
- 3 继承写法如下,上面的Child类想继承父类,改成如下写法就好
注意写了extends关键字,constructor中就必须写super()
,打印结果如下:
The above is the detailed content of JavaScript prototype and inheritance are a must for interviews. 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



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

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).

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

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
