>  기사  >  웹 프론트엔드  >  js의 세 가지 상속 방법과 그 장점과 단점

js의 세 가지 상속 방법과 그 장점과 단점

怪我咯
怪我咯원래의
2017-06-29 11:03:051168검색

아래 편집자는 js의 세 가지 상속 방법과 그 장점과 단점에 대해 간략하게 설명합니다. 에디터가 꽤 괜찮다고 생각해서 지금 공유하고 참고용으로 보도록 하겠습니다. 첫 번째는 프로토타입 방법입니다.

//父类 
function person(){ 
  this.hair = 'black'; 
  this.eye = 'black'; 
  this.skin = 'yellow'; 
  this.view = function(){ 
    return this.hair + ',' + this.eye + ',' + this.skin; 
  } 
} 

//子类 
function man(){ 
  this.feature = ['beard','strong']; 
} 

man.prototype = new person(); 
var one = new man(); 

console.log(one.feature); //['beard','strong'] 
console.log(one.hair); //black 
console.log(one.eye); //black 
console.log(one.skin); //yellow 
console.log(one.view()); //black,black,yellow
이 방법이 가장 간단합니다. , 하위 클래스의 프로토타입 속성 값을 상속된 인스턴스에 할당하기만 하면 상속된 클래스의 메서드를 직접 사용할 수 있습니다. prototype 속성은 무엇을 의미하나요? 프로토타입은 프로토타입입니다. (함수로 정의된) 모든 객체에는 객체 유형인 기본 프로토타입 속성이 있습니다.

그리고 이 기본 속성은 체인의 상향 검색을 구현하는 데 사용됩니다. 즉, 객체의 속성이 존재하지 않는 경우 프로토타입 속성이 속한 객체를 통해 속성을 찾는다는 의미입니다. 프로토타입을 찾을 수 없으면 어떻게 되나요?

js는 프로토타입의 프로토타입 속성이 속한 객체를 자동으로 검색하여 해당 속성이 발견되거나 프로토타입이 최종적으로 비어 있을 때까지("정의되지 않음"

) 프로토타입

index

을 통해 이동합니다. 예를 들어, 위의 예에서는 한 인스턴스의 one.view() 메서드에 대해 js는 먼저 한 인스턴스에 view() 메서드가 있는지 확인합니다. 왜냐하면 man.prototype 속성을 찾습니다. 그리고 프로토타입의 값은 person의 인스턴스입니다. 이 인스턴스에는 view() 메서드가 있으므로 호출이 성공합니다.

두 번째 적용 방법:

//父类 
function person(){ 
  this.hair = 'black'; 
  this.eye = 'black'; 
  this.skin = 'yellow'; 
  this.view = function(){ 
    return this.hair + ',' + this.eye + ',' + this.skin; 
  } 
} 

//子类 
function man(){ 
  // person.apply(this,new Array()); 
  person.apply(this,[]); 
  this.feature = ['beard','strong']; 
} 

var one = new man(); 

console.log(one.feature); //['beard','strong'] 
console.log(one.hair); //black 
console.log(one.eye); //black 
console.log(one.skin); //yellow 
console.log(one.view()); //black,black,yellow
참고: 적용 매개변수가 비어 있는 경우, 즉 매개변수가 전달되지 않은 경우 new Array(), []를 통해 전달되며 null은 유효하지 않습니다.

세 번째 메소드인 call+prototype:

//父类 
function person(){ 
  this.hair = 'black'; 
  this.eye = 'black'; 
  this.skin = 'yellow'; 
  this.view = function(){ 
    return this.hair + ',' + this.eye + ',' + this.skin; 
  } 
} 

//子类 
function man(){ 
  // person.apply(this,new Array()); 
  person.call(this,[]); 
  this.feature = ['beard','strong']; 
} 

man.prototype = new person(); 
var one = new man(); 

console.log(one.feature); //['beard','strong'] 
console.log(one.hair); //black 
console.log(one.eye); //black 
console.log(one.skin); //yellow 
console.log(one.view()); //black,black,yellow
call 메소드의 구현 메커니즘에는 man.prototype = new person();이 하나 더 필요합니다. 호출 메소드는 메소드 교체만 구현하고 객체 속성을 복사하지 않기 때문입니다. Google Map API의 상속은 이 방법을 사용합니다.


위에는 세 가지 상속 방법의 구현이 요약되어 있습니다. 그러나 각 방법에는 장단점이 있습니다.

상위 클래스가 다음과 같은 경우:

//父类 
function person(hair,eye,skin){ 
  this.hair = hair; 
  this.eye = eye; 
  this.skin = skin; 
  this.view = function(){ 
    return this.hair + ',' + this.eye + ',' + this.skin; 
  } 
}
하위 클래스 남자가

객체 생성

동안 ​​상위 클래스 사람에게 매개변수를 전달할 수 있도록 하위 클래스를 어떻게 설계해야 합니까? 프로토타입의 상속 방법은 적용되지 않습니다.

Apply를 사용해야 합니다. 또는 호출 방법:

//apply方式 
//子类 
function man(hair,eye,skin){ 
  person.apply(this,[hair,eye,skin]); 
  this.feature = ['beard','strong']; 
} 
//call方式 
//子类 
function man(hair,eye,skin){ 
  person.call(this,hair,eye,skin); 
  this.feature = ['beard','strong']; 
}
그런데 Apply 방법을 사용하는 데 여전히 단점이 있습니다. 이유는 무엇입니까? js에는 "instanceof"라는 매우 중요한 연산자
가 있습니다. 이 연산자는 객체가 특정 유형인지 비교하는 데 사용됩니다.

이 예에서는 man 유형 외에 하나의 인스턴스도 person 유형이어야 합니다. 그러나 apply 메소드에서 상속한 후에는 person 유형에 속하지 않습니다. 즉, ( one instanceof person)은 거짓입니다.
결국 가장 좋은 상속 방법은 호출+프로토타입 방법입니다. 그런 다음 (BaseClass 인스턴스 하나)의 값이 true인지 시험해 볼 수 있습니다.

세 번째 상속 방법에도 결함이 있습니다. 새 개체를 서브클래싱할 때 부모 클래스에 필요한 매개 변수를 전달해야 하며 부모 클래스의

속성 및 메서드
가 재현됩니다. 다음 상속 방법은 완벽합니다. :

function Person(name){   
  this.name = name; 
} 

Person.prototype.getName = function() { 
  return this.name; 
} 

function Chinese(name, nation) { 
  Person.call(this, name); 
  this.nation = nation; 
} 

//继承方法 
function inherit(subClass, superClass) { 
  function F() {} 
  F.prototype = superClass.prototype; 
  subClass.prototype = new F(); 
  subClass.prototype.constructor = subClass.constructor; 
} 

inherit(Chinese, Person); 

Chinese.prototype.getNation = function() { 
  return this.nation; 
}; 

var p = new Person('shijun'); 
var c = new Chinese("liyatang", "China"); 

console.log(p); // Person {name: "shijun", getName: function} 
console.log(c); // Chinese {name: "liyatang", nation: "China", constructor: function, getNation: function, getName: function} 


console.log(p.constructor); // function Person(name){} 
console.log(c.constructor); // function Chinese(){} 

console.log(c instanceof Chinese); // true 
console.log(c instanceof Person); // true

위 내용은 js의 세 가지 상속 방법과 그 장점과 단점의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.