JavaScript 상속의 프로토타입 체인 및 차용 생성자 사용 예에 ​​대한 자세한 설명

伊谢尔伦
풀어 주다: 2017-07-25 15:59:10
원래의
1407명이 탐색했습니다.

프로토타입 체인

JavaScript에서 상속을 구현하는 가장 간단한 방법은 프로토타입 체인을 사용하는 것입니다. 하위 유형의 프로토타입을 상위 유형의 인스턴스로 지정하면 됩니다. 즉, "subtype.prototype = 새 상위 유형( );"를 달성하기 위한 방법은 다음과 같습니다.


// 为父类型创建构造函数
function SuperType() {
  this.name = ['wuyuchang', 'Jack', 'Tim'];
  this.property = true;
}

// 为父类型添加方法
SuperType.prototype.getSuerperValue = function() {
  return this.property;
}

// 为子类型创建构造函数
function SubType() {
  this.test = ['h1', 'h2', 'h3', 'h4'];
  this.subproperty = false;
}

// 实现继承的关键步骤,子类型的原型指向父类型的实例
SubType.prototype = new SuperType();

// 在此处给子类型添加方法,一定要在实现继承之后,否则会在将指针指向父类型的实例,则方法为空
SubType.prototype.getSubValue = function() {
  return this.subproperty;
}


/* 以下为测试代码示例 */
var instance1 = new SubType();
instance1.name.push('wyc');
instance1.test.push('h5');
alert(instance1.getSuerperValue());    // true
alert(instance1.getSubValue());      // false
alert(instance1.name);          // wuyuchang,Jack,Tim,wyc
alert(instance1.test);          // h1,h2,h3,h4,h5


var instance2 = new SubType();
alert(instance2.name);          // wuyuchang,Jack,Tim,wyc
alert(instance2.test);          // h1,h2,h3,h4
로그인 후 복사

위 코드는 프로토타입 체인을 통해 구현한 단순 상속임을 알 수 있지만, 테스트 코드 예시에서는 여전히 몇 가지 문제가 남아 있습니다. 내 블로그 게시물 "객체 지향 JS, 팩토리 모드, 생성자 모드, 프로토타입 모드, 하이브리드 모드, 동적 프로토타입 모드에 대한 기본 설명"을 읽은 아이들은 프로토타입 체인 코드의 첫 번째 문제가 프로토타입 체인 코드의 프로토타입이라는 것을 알아야 한다고 믿습니다. 하위 유형은 상위 유형의 인스턴스, 즉 하위 유형의 프로토타입에 포함된 상위 유형의 속성이므로 참조 유형 값의 프로토타입 속성이 모든 인스턴스에서 공유됩니다. 위 코드의 instance1.name.push('wyc');는 이 문제의 존재를 증명할 수 있습니다. 프로토타입 체인의 두 번째 문제점은 하위 유형의 인스턴스를 생성할 때 매개변수를 상위 유형의 생성자에 전달할 수 없다는 것입니다. 따라서 실제 개발에서는 프로토타입 체인만 단독으로 사용하는 경우가 거의 없습니다.

생성자 차용

 프로토타입 체인에 존재하는 두 가지 문제를 해결하기 위해 개발자들은 프로토타입 체인에 존재하는 문제를 해결하기 위해 생성자 차용이라는 기술을 사용하기 시작했습니다. 이 기술의 구현 아이디어도 매우 간단합니다. 하위 유형의 생성자 내에서 상위 유형의 생성자를 호출하기만 하면 됩니다. 함수는 특정 환경에서 코드를 실행하는 객체일 뿐이므로 생성자는 apply() 또는 call() 메서드를 통해 실행될 수 있습니다. 코드는 다음과 같습니다.


// 为父类型创建构造函数
function SuperType(name) {
  this.name = name;
  this.color = ['pink', 'yellow'];
  this.property = true;

  this.testFun = function() {
    alert('http://tools.jb51.net/');
  }
}

// 为父类型添加方法
SuperType.prototype.getSuerperValue = function() {
  return this.property;
}

// 为子类型创建构造函数
function SubType(name) {
  SuperType.call(this, name);
  this.test = ['h1', 'h2', 'h3', 'h4'];
  this.subproperty = false;
}

// 在此处给子类型添加方法,一定要在实现继承之后,否则会在将指针指向父类型的实例,则方法为空
SubType.prototype.getSubValue = function() {
  return this.subproperty;
}


/* 以下为测试代码示例 */
var instance1 = new SubType(['wuyuchang', 'Jack', 'Nick']);
instance1.name.push('hello');
instance1.test.push('h5');
instance1.color.push('blue');
instance1.testFun();            // http://tools.jb51.net/
alert(instance1.name);            // wuyuchang,Jack,Nick,hello
// alert(instance1.getSuerperValue());    // error 报错
alert(instance1.test);            // h1,h2,h3,h4,h5    
alert(instance1.getSubValue());        // false    
alert(instance1.color);            // pink,yellow,blue

var instance2 = new SubType('wyc');
instance2.testFun();            // http://tools.jb51.net/
alert(instance2.name);            // wyc    
// alert(instance2.getSuerperValue());    // error 报错
alert(instance2.test);            // h1,h2,h3,h4
alert(instance2.getSubValue());        // false
alert(instance2.color);            // pink,yellow
로그인 후 복사

위 코드에서 하위 유형 SubType의 생성자가 상위 유형인 "SuperType.call(this, name);"을 호출하여 속성 상속을 구현하는 것을 볼 수 있으며, 하위 유형에서도 사용할 수 있습니다. 인스턴스를 생성할 때 상위 유형에 대한 매개변수가 전달되지만 새로운 문제가 다시 발생합니다. 상위 유형의 생성자 testFun에 메서드를 정의하고 상위 유형의 프로토타입에 getSuperValue라는 메서드를 정의한 것을 볼 수 있습니다. 그러나 하위 유형을 인스턴스화한 후에도 상위 유형의 프로토타입에 정의된 getSuperValue 메소드를 호출할 수 없습니다. 상위 유형의 생성자 메소드인 testFun만 호출할 수 있습니다. 이는 객체를 생성할 때 생성자 패턴만 사용하여 함수를 재사용할 수 없게 만드는 것과 같습니다. 이러한 문제를 고려하여 생성자를 빌리는 기술은 단독으로 사용되는 경우가 거의 없습니다.

결합 상속(프로토타입 체인 + 빌린 생성자)

이름에서 알 수 있듯이 결합 상속은 프로토타입 체인과 빌린 생성자의 장점을 결합한 패턴입니다. 구현도 매우 간단합니다. 결합이기 때문에 확실히 양쪽의 장점을 결합합니다. 즉, 프로토타입 체인이 메서드를 상속하고 생성자가 속성을 상속합니다. 구체적인 코드 구현은 다음과 같습니다.


// 为父类型创建构造函数
function SuperType(name) {
  this.name = name;
  this.color = ['pink', 'yellow'];
  this.property = true;

  this.testFun = function() {
    alert('http://tools.jb51.net/');
  }
}

// 为父类型添加方法
SuperType.prototype.getSuerperValue = function() {
  return this.property;
}

// 为子类型创建构造函数
function SubType(name) {
  SuperType.call(this, name);
  this.test = ['h1', 'h2', 'h3', 'h4'];
  this.subproperty = false;
}

SubType.prototype = new SuperType();

// 在此处给子类型添加方法,一定要在实现继承之后,否则会在将指针指向父类型的实例,则方法为空
SubType.prototype.getSubValue = function() {
  return this.subproperty;
}


/* 以下为测试代码示例 */
var instance1 = new SubType(['wuyuchang', 'Jack', 'Nick']);
instance1.name.push('hello');
instance1.test.push('h5');
instance1.color.push('blue');
instance1.testFun();            // http://tools.jb51.net/
alert(instance1.name);            // wuyuchang,Jack,Nick,hello
alert(instance1.getSuerperValue());      // true
alert(instance1.test);            // h1,h2,h3,h4,h5    
alert(instance1.getSubValue());        // false    
alert(instance1.color);            // pink,yellow,blue

var instance2 = new SubType('wyc');
instance2.testFun();            // http://tools.jb51.net/
alert(instance2.name);            // wyc    
alert(instance2.getSuerperValue());      // true
alert(instance2.test);            // h1,h2,h3,h4
alert(instance2.getSubValue());        // false
alert(instance2.color);            // pink,yellow
로그인 후 복사

위 코드는 SuperType.call(this, name)을 통해 상위 유형의 속성을 상속하고 SubType.prototype = new SuperType(을 통해 상위 유형의 메서드를 상속합니다. );. 위의 코드는 프로토타입 체인과 빌린 생성자에서 발생하는 문제를 편리하게 해결하며 JavaScript에서 가장 일반적으로 사용되는 인스턴스 상속 방법이 되었습니다.

위 내용은 JavaScript 상속의 프로토타입 체인 및 차용 생성자 사용 예에 ​​대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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