ES6 클래스 및 상속의 구현 원칙(코드 예제)

不言
풀어 주다: 2019-01-10 10:47:40
앞으로
3509명이 탐색했습니다.

이 기사에서 제공하는 내용은 ES6 클래스의 구현 원칙(코드 예제)에 대한 것이며, 특정 참조 가치가 있으므로 도움이 필요한 친구에게 도움이 되기를 바랍니다.

1.es6 클래스 사용

javascript는 프로토타입 상속을 사용합니다.
es6은 객체지향 상속과 같은 구문적 설탕을 제공합니다.

class Parent {
  constructor(a){
    this.filed1 = a;
  }
  filed2 = 2;
  func1 = function(){}
}

class Child extends Parent {
    constructor(a,b) {
      super(a);
      this.filed3 = b;
    }
  
  filed4 = 1;
  func2 = function(){}
}
로그인 후 복사

바벨을 사용하여 es6 클래스와 상속의 구현 원리를 살펴보겠습니다.

1. 클래스 구현

변환 전:

class Parent {
  constructor(a){
    this.filed1 = a;
  }
  filed2 = 2;
  func1 = function(){}
}
로그인 후 복사

변환 후:

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var Parent = function Parent(a) {
  _classCallCheck(this, Parent);

  this.filed2 = 2;

  this.func1 = function () { };

  this.filed1 = a;
};
로그인 후 복사

클래스의 맨 아래 레이어가 여전히 생성자임을 알 수 있습니다.

1. 현재 함수 호출 전의 새 키워드.

생성자가 실행되기 전에 new 키워드가 있으면 생성자 내부에 빈 개체가 생성되고, 생성자의 proptype은 빈 개체의 _proto_를 가리키며, 이는 빈 개체를 가리킵니다. 위와 같이 _classCallCheck에서 이 Parent 인스턴스는 true를 반환합니다.

생성자 앞에 new가 없으면 생성자의 proptype이 이것의 프로토타입 체인에 나타나지 않고 false가 반환됩니다.

2. 클래스 내부의 변수와 함수를 this에 할당합니다.

3. 생성자 내부에서 로직을 실행합니다.

4. 이것을 반환합니다(생성자는 기본적으로 마지막에 수행됩니다).

2. 상속 구현

변환 전:

class Child extends Parent {
    constructor(a,b) {
      super(a);
      this.filed3 = b;
    }
  
  filed4 = 1;
  func2 = function(){}
}
로그인 후 복사

변환 후:

먼저 Child의 내부 구현을 살펴본 다음 내부에서 호출되는 함수가 어떻게 구현되는지 살펴보겠습니다.

var Child = function (_Parent) {
  _inherits(Child, _Parent);

  function Child(a, b) {
    _classCallCheck(this, Child);

    var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, a));

    _this.filed4 = 1;

    _this.func2 = function () {};

    _this.filed3 = b;
    return _this;
  }

  return Child;
}(Parent);
로그인 후 복사

1. 함수 상속 상위 클래스의 proptype입니다.

_inherits 내부 구현:

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: { value: subClass, enumerable: false, writable: true, configurable: true }
  });
  if (superClass)
    Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
로그인 후 복사

(1) 상위 생성자를 확인합니다.

(2) 일반적인 기생 상속: 상위 클래스 생성자의 proptype을 사용하여 빈 객체를 만들고 이 객체가 하위 클래스 생성자의 proptype을 가리킵니다.

(3) 부모 생성자를 자식 생성자의 _proto_에 지정합니다(이 단계가 무엇을 하는지는 확실하지 않으며 의미가 없다고 느껴집니다.)

2. 클로저를 사용하여 클로저 내부에 부모 클래스 참조를 저장합니다. 하위 클래스 구성 논리.

3.새 체크.

4. 현재 this를 사용하여 상위 클래스 생성자를 호출합니다.

var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, a));
로그인 후 복사

The Child.__proto__ || Object.getPrototypeOf(Child)는 실제로 상위 생성자(_inherits의 마지막 작업)이며 호출을 통해 호출자를 현재 this로 변경하고 매개 변수를 전달합니다. (여기서 직접 전달한 Parent를 사용해도 될 것 같습니다.)

function _possibleConstructorReturn(self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
로그인 후 복사

이것이 초기화되었는지, super가 호출되었는지 확인하고, 부모 클래스에서 할당한 것을 반환합니다.

5. 여기에 행 하위 클래스 내부의 변수와 함수를 할당합니다.

6. 하위 클래스 생성자 내부에서 논리를 실행합니다.

es6이 실제로 "결합된 기생 상속"을 작성하는 간단한 방법을 제공한다는 것을 알 수 있습니다.

3. super

super는 상위 클래스 생성자를 나타냅니다.

super.fun1()은 Parent.fun1() 또는 Parent.prototype.fun1()과 동일합니다.

super()는 Parent.prototype.construtor()와 동일합니다

하위 클래스 생성자를 작성하지 않을 때:

var Child = function (_Parent) {
  _inherits(Child, _Parent);

  function Child() {
    _classCallCheck(this, Child);

    return _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).apply(this, arguments));
  }

  return Child;
}(Parent);
로그인 후 복사

기본 생성자가 적극적으로 부모 클래스 생성자를 호출하고 현재 생성자를 다음과 같이 전달하는 것을 볼 수 있습니다. default 매개변수는 상위 클래스에 전달됩니다.

따라서 생성자를 선언할 때 super()를 적극적으로 호출해야 합니다. 그렇지 않으면 상위 생성자를 호출할 수 없고 상속이 완료될 수 없습니다.

전형적인 예는 Reatc의 Component에 있습니다. 생성자 선언 후 super(props)를 호출해야 합니다. 왜냐하면 부모 클래스는 생성자의 props에 대해 일부 초기화 작업을 수행해야 하기 때문입니다.

위 내용은 ES6 클래스 및 상속의 구현 원칙(코드 예제)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:segmentfault.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!