Table of Contents
# What is the principle of ##instanceof? Let’s first look at using
Home Web Front-end JS Tutorial JavaScript prototype and inheritance are a must for interviews

JavaScript prototype and inheritance are a must for interviews

Dec 01, 2020 pm 05:40 PM
javascript

javascriptThe column introduces prototypes and inheritance that must be learned in interviews

JavaScript prototype and inheritance are a must for interviews

##Related free learning recommendations:

javascript( Video)

This article starts from the following aspects

  • 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)
0 How to understand object-oriented

In fact, I also I don’t know how to answer this question. I only know that after the interviewer asks this, it means that he is going to ask a bunch of inheritance questions. The following is a quote from Teacher Zhou.

"Object-oriented is a programming idea that corresponds to process-oriented. General languages ​​​​are object-oriented. JS itself is also built based on object-oriented. For example, js itself has many built-in classes, and Promise is, You can use new Promise to create an instance to manage asynchronous programming. The same is true for vue. Usually, instances of vue are created."

1 How to create objects

1. Object literal

var o1 = {name: 'o1'}
var o2 = new Object({name: 'o2'})
Copy after login
2. Through the constructor

var M = function(name){
    this.name = name
}
var o3 = new M('o3')
Copy after login
3.Object.create

var o4 = Object.create(p)
Copy after login
2 Tips to remember the prototype chain

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 fact

Constructor, Instance, constructor, __ proto__, prototype are already related in the above example and 3 points That’s it in the introduction. Let’s review again

  1. The constructor is an ordinary function, but there is the new keyword in front

  2. Through

    new Add constructor , and the generated object is an instance.

  3. 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
  4. 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 clearer

3 instanceof simulation implementation

# What is the principle of ##instanceof? Let’s first look at using

[] instanceof Array  // true
Copy after login

. 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
Copy after login

Then implement instanceof based on this idea, you will definitely be more impressed

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
4 new simulation implementation (brief version)

new process happened What?

    Generate an empty object
  1. The
  2. proto

    of this empty object is assigned to the prototype of the constructor

  3. Bind this to point to
  4. Return this object
  5.  // 构造函数
     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 login

  6. 5 Implementation of inheritance (step by step implementation)

Step by step, from simple to complex, you can more intuitively discover the principles and shortcomings of inheritance

    Construction method core Parent1.call(this)
  1.  // 构造方法方式
     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

Disadvantages: Only the internal properties of the parent class constructor can be inherited, and the properties on the prototype object of the parent class constructor cannot be inherited

Thinking: Why does call implement inheritance? What is the essence of call?

    Only inherit the core through prototype Child2.prototype = new Parent2()
  1.  // 原型
     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

Disadvantages: c21.arr and c22.arr corresponds to the same reference

Thinking: Why is it written like this to be the same reference?

Combined inheritance 1
Combine the advantages of the above two inheritance methods and discard the disadvantages

 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
Thinking: Is there no problem if I write like this?

答 : 生成一个实例要执行 Parent3.call(this) , new Child3(),也就是Parent3执行了两遍。

  1. 组合继承2

改变上例子 的

  Child3.prototype = new Parent3()
Copy after login

  Child3.prototype = Parent3.prototype
Copy after login

缺点 : 很明显,无法定义子类构造函数原型私有的方法

  1. 组合继承优化3 再次改变上例子 的

    Child3.prototype = Parent3.prototype
    Copy after login

   Child3.prototype = Object.create(Parent3.prototype)
Copy after login

问题就都解决了。 因为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
Copy after login

所以回想起文章开头所说的那几个需要牢记的点,就需要重新赋值一下子类构造函数的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)
Copy after login

5 es6的继承

class Parent{
  constructor(name) {
    this.name = name
  }
  getName(){
    return this.name
  }
}

class Child{
  constructor(age) {
    this.age = age
  }
  getAge(){
    return this.age
  }
}
Copy after login

es6继承记住几个注意事项吧

  • 1 构造函数不能当普通函数一样执行 Parent() 是会报错的
  • 2 不允许重定向原型 Child.prototype = Object.create(Parent.prototype) 无用
  • 3 继承写法如下,上面的Child类想继承父类,改成如下写法就好

JavaScript prototype and inheritance are a must for interviewsJavaScript prototype and inheritance are a must for interviews


注意写了extends关键字,constructor中就必须写super(),打印结果如下:

JavaScript prototype and inheritance are a must for interviews

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

See all articles