>  기사  >  웹 프론트엔드  >  인터뷰에는 자바스크립트 프로토타입과 상속이 필수

인터뷰에는 자바스크립트 프로토타입과 상속이 필수

coldplay.xixi
coldplay.xixi앞으로
2020-12-01 17:40:412730검색

javascript 칼럼에서는 면접에서 꼭 배워야 할 프로토타입과 상속을 소개합니다

인터뷰에는 자바스크립트 프로토타입과 상속이 필수

관련 무료 학습 추천 : javascript(동영상)

이 글은 다음과 같은 측면에서 시작됩니다

  • 0이해하는 방법 객체 지향
  • 1 객체 생성 방법
  • 2 프로토타입 체인을 기억하는 팁
  • 3시뮬레이션 구현 인스턴스
  • 4새로운 키워드 시뮬레이션 구현
  • 5상속 구현(단계별 구현)

0 객체지향을 이해하는 방법

사실 저는 이 질문에 어떻게 대답해야 할지 모르겠어요. 면접관이 이렇게 물어본 후에는 상속 관련 질문을 잔뜩 하겠다는 뜻이라는 것만 알았어요. 다음은 조 선생님의 말씀입니다.

"객체 지향은 프로세스 지향에 해당하는 프로그래밍 아이디어입니다. 일반 언어도 객체 지향입니다. JS 자체도 객체 지향을 기반으로 구축되었습니다. 예를 들어 js 자체에는 많은 내장 클래스가 있습니다. , Promise와 같은 인스턴스를 생성하여 비동기 프로그래밍을 관리할 수 있습니다. 그리고 vue는 vue의 인스턴스도 생성합니다. "

1 객체 리터럴

var o1 = {name: 'o1'}
var o2 = new Object({name: 'o2'})

2. 생성자를 통해

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

3. .Object.create

var o4 = Object.create(p)

2 프로토타입 체인 기억을 위한 팁

기억은 항상 규칙적입니다. 예를 들어 고등학교에서 배운 삼각함수는 많은 공식을 외우면 헷갈리기 쉽습니다. 당신은 모든 공식을 억지로 외웁니다. 하지만 핵심 내용을 외우면 나머지 공식은 약간의 도출만 필요합니다. 프로토타입 체인도 마찬가지입니다. 처음에 몇 가지 사항을 기억해두면 나중에 헷갈릴 일이 없습니다. 프로토타입 체인의 주요 개념:
constructor

, instance, constructor, __ proto__, prototype, 우선 그들의 관계를 기억하세요

인스턴스(객체)는
    proto
  • , 인스턴스( Object)에는 프로토타입이 없습니다생성자에는 프로토타입이 있고 프로토타입은 객체이므로 프로토타입은 위의
  • proto
  • 를 갖는 것 외에도 생성자의 생성자를 포함합니다. 생성자의 프로토타입은 생성자 자체를 가리키고 있습니다. 즉, 위의 예에서는 M.prototype.constructor === M
위의 세 가지 사항을 명심하세요. 나중에 요약되는 완전한 상속은 밀접한 관련이 있습니다. to this

사실
constructor

, instance, constructor , __ proto__, prototype의 관계는 위의 예와 3가지 소개에서 소개되었습니다. 다시 검토해 보겠습니다

    생성자는 앞에 new 키워드가 있다는 점을 제외하면 일반적인 함수입니다.
  1. new

    constructor를 더하면 생성된 객체는 인스턴스입니다.

  2. 위에서 생성된 o3 인스턴스를 예로 들어보겠습니다
  3.  o3.__proto__ === M.prototype  //true
    
     o3.prototype   //undefined
    
     o3.__proto__ === M.prototype //true

  4. o3 인스턴스 자체에는 생성자가 없지만 프로토타입 체인의 도움으로 위쪽으로 검색됩니다. 즉,
  5.  o3.constructor === M.prototype.constructor  // true
    
     o3.constructor === M //true

이러한 키워드 간의 관계를 정리하면 프로토타입 체인이 훨씬 더 명확해집니다

3개 인스턴스오브 시뮬레이션 구현

인스턴스오브의 원리는 무엇인가요? 먼저

[] instanceof Array  // true

를 사용하는 방법을 살펴보겠습니다. 즉, 객체는 왼쪽에 있고 유형은 오른쪽에 있습니다. 인스턴스 오브는 오른쪽 인스턴스의 프로토타입 체인에 있는지 여부를 확인하는 것입니다. 다음 예시

[].__proto__ === Array.prototype //true
Array.prototype.__proto__ === Object.prototype //true
Object.prototype__proto__ //null

그렇다면 이 아이디어를 바탕으로 인스턴스 오브를 구현해 보면 분명 더 감동받을 것입니다

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 새로운 시뮬레이션 구현(간단 버전)

뉴 과정에서 무슨 일이 일어났나요?

    빈 객체 생성
  1. 이 빈 객체의
  2. proto

    는 생성자의 프로토타입에 할당됩니다.

  3. 이 객체를 가리키도록 바인딩
  4. 이 객체 반환
  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 상속( 단계별 구현)의 구현

단계별로 간단한 것부터 복잡한 것까지 상속의 원리와 단점을 보다 직관적으로 발견할 수 있습니다

    구성 방법 핵심 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() //报错

단점: 부모만 상속 가능 클래스 생성자의 내부 속성은 부모 클래스 생성자의 프로토타입 객체에 있는 속성을 상속할 수 없습니다.

생각: 호출이 상속을 구현하는 이유는 무엇입니까? ?

    프로토타입 상속 코어에만 의존 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)

단점: c21.arr 및 c22.arr은 동일한 참조에 해당합니다

생각: 왜 다음과 같이 작성됩니까? 이거요?

결합 상속 1
위의 두 상속 방법의 장점을 결합하고 단점은 모두 버려요

 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)
생각: 이렇게 써도 문제 없나요?

答 : 生成一个实例要执行 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类想继承父类,改成如下写法就好

인터뷰에는 자바스크립트 프로토타입과 상속이 필수인터뷰에는 자바스크립트 프로토타입과 상속이 필수


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

인터뷰에는 자바스크립트 프로토타입과 상속이 필수

위 내용은 인터뷰에는 자바스크립트 프로토타입과 상속이 필수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 jianshu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제