Home>Article>Web Front-end> JavaScript prototype and inheritance are a must for interviews

JavaScript prototype and inheritance are a must for interviews

coldplay.xixi
coldplay.xixi forward
2020-12-01 17:40:41 2725browse

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'})
2. Through the constructor

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

var o4 = Object.create(p)
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__,prototypeare 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

    newAddconstructor, 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
  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
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

. 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

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

  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() //报错

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)

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

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

  1. 组合继承2

改变上例子 的

Child3.prototype = new Parent3()

Child3.prototype = Parent3.prototype

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

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

    Child3.prototype = Parent3.prototype

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类想继承父类,改成如下写法就好

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:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete