>  기사  >  웹 프론트엔드  >  객체지향 자바스크립트, javascript_javascript 스킬로 상속 구현 방법을 배워보세요.

객체지향 자바스크립트, javascript_javascript 스킬로 상속 구현 방법을 배워보세요.

WBOY
WBOY원래의
2016-05-16 15:22:061069검색

본 글의 예시에서는 자바스크립트에서 상속을 구현하는 6가지 방법을 소개하고 있으며, 구체적인 내용은 다음과 같습니다

1. [프로토타입 체인 상속] 구현의 핵심은 프로토타입 객체를 다시 작성하고 이를 새로운 유형의 인스턴스로 바꾸는 것입니다. 실제로 다시 작성된 것은 SubType 프로토타입의 생성자 속성이 아니지만 SubType 프로토타입은 다른 개체인 SuperType 프로토타입을 가리키고 이 프로토타입 개체의 생성자 속성은 SuperType
을 가리킵니다.

function SuperType(){
 this.property = true;
}
SuperType.prototype.getSuperValue = function(){
 return this.property;
};
function SubType(){
 this.subproperty = false;
}
//继承了SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
 return this.subproperty;
}
var instance = new SubType();
alert(instance.getSuperValue());//true

[참고 1] 메소드를 신중하게 정의하고, 프로토타입에 메소드를 추가하는 코드는 프로토타입을 대체하는 명령문 뒤에 위치해야 합니다

function SuperType(){
 this.property = true;
}
SuperType.prototype.getSuperValue = function(){
 return this.property;
};
function SubType(){
 this.subproperty = false;
}
//继承了SuperType
SubType.prototype = new SuperType();

//添加了新方法
SubType.prototype.getSubValue = function(){
 return this.subproperty;
}
//重写超类型的方法
SubType.prototype.getSuperValue = function(){
 return false;
}
var instance = new SubType();
alert(instance.getSuperValue());//false

[참고 2] 프로토타입 체인을 통해 상속을 구현할 때 객체 리터럴을 사용하여 프로토타입 메서드를 생성할 수 없습니다.

function SuperType(){
 this.property = true;
}
SuperType.prototype.getSuperValue = function(){
 return this.property;
};
function SubType(){
 this.subproperty = false;
}
//继承了SuperType
SubType.prototype = new SuperType();

//使用字面量方法添加新方法会导致上一行代码无效
SubType.prototype = {
 getSubValue : function(){
  return this,subproperty;
 },
 someOtherMethod : function(){
  return false;
 }
};
var instance = new SubType();
alert(instance.getSuperValue());//error

[단점 1] 하위 유형의 인스턴스 생성 시 상위 유형의 생성자에 매개변수를 전달할 수 없습니다.
[단점 2] 참조 유형 값이 포함된 프로토타입 속성은 모든 인스턴스에서 공유됩니다

function SuperType(){
 this.colors = ['red','blue','green'];
}
function SubType(){}
//继承了SuperType
SubType.prototype = new SuperType();
var instance1 = new SubType();
instance1.colors.push('black');
alert(instance1.colors);//'red,blue,green,black'
var instance2 = new SubType();
alert(instance2.colors);//'red,blue,green,black'

2. [빌린 생성자 상속(가짜 객체 또는 클래식 상속이라고도 함)]은 하위 유형 생성자 내부에서 상위 유형 생성자를 호출하므로 apply() 및 call() 메서드를 사용하여 생성자를 호출할 수도 있습니다. 앞으로 새로 생성되는 개체에 대해 실행

function SuperType(){
 this.colors = ['red','blue','green'];
}
function SubType(){
 //继承了SuperType
 SuperType.call(this);
}
var instance1 = new SubType();
instance1.colors.push('black');
alert(instance1.colors);//'red,blue,green,black'
var instance2 = new SubType();
alert(instance2.colors);//'red,blue,green'

[장점] 패스 매개변수

function SuperType(name){
 this.name = name;
}
function SubType(){
 //继承了SUperType,同时还传递了参数
 SuperType.call(this,"Nicholas");
 //实例属性
 this.age = 29;
}
var instance = new SubType();
alert(instance.name);//"Nicholas"
alert(instance.age);//29 

[참고] SuperType 생성자가 하위 유형의 속성을 재정의하지 않도록 하려면 상위 유형 생성자를 호출한 후 하위 유형에서 정의해야 하는 속성을 추가할 수 있습니다.

function SuperType(name){
 this.name = name;
 this.age = 30;
}
function SubType(){
 //实例属性
 this.age = 29;
 //继承了SUperType,同时还传递了参数
 SuperType.call(this,"Nicholas");
}
var instance = new SubType();
//实例属性被重写为SuperType构造函数的属性
alert(instance.age);//30

[단점 1] 기능 재사용이 불가능하다
[단점 2] 슈퍼타입의 프로토타입에 정의된 메소드는 서브타입에도 보이지 않기 때문에 모든 타입은 생성자 패턴만 사용할 수 있습니다
3. [결합 상속(의사 고전 상속이라고도 함)] 프로토타입 연결 기술과 생성자 차용 기술을 결합하여 두 기술의 장점을 모두 활용하는 상속 모델입니다. 그 뒤에 있는 아이디어는 프로토타입 체인을 사용하여 프로토타입 속성과 메서드의 상속을 달성하고 생성자를 빌려 인스턴스 속성의 상속을 달성하는 것입니다. 이런 방식으로 함수 재사용은 프로토타입에 메서드를 정의함으로써 이루어지며, 각 인스턴스는 고유한 속성을 가지도록 보장될 수 있어 JavaScript에서 가장 일반적으로 사용되는 상속 패턴이 됩니다.

function SuperType(name){
 this.name = name;
 this.colors = ['red','blue','green'];
}
SuperType.prototype.sayName = function(){
 alert(this.name);
};
function SubType(name,age){
 //继承属性
 SuperType.call(this,name);
 this.age = age;
}
//继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
 alert(this.age);
}
var instance1 = new SubType("Nicholas",29);
instance1.colors.push("black");
alert(instance1.colors);//'red,blue,green,black'
instance1.sayName();//"Nicholas"
instance1.sayAge();//29
var instance2 = new SubType("Greg",27);
alert(instance2.colors);//'red,blue,green'
instance2.sayName();//"Greg"
instance2.sayAge();//27

[단점] 어쨌든 상위 유형 생성자는 하위 유형 프로토타입을 생성할 때 한 번, 하위 유형 생성자 내부에서 한 번, 두 번 호출됩니다. 하위 유형은 결국 상위 유형 객체의 모든 인스턴스 속성을 포함하지만 하위 유형 생성자가 호출될 때 이러한 속성을 재정의해야 합니다.

function SuperType(name){
 this.name = name;
 this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
 alert(this.name);
};
function SubType(name,age){
 SuperType.call(this,name); // 第二次调用SuperType()
 this.age = age;
}
SubType.prototype = new SuperType(); //第一次调用SuperType()
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
 alert(this.age);
}; 

4. [프로토타입 상속] 프로토타입을 사용하면 사용자 정의 유형을 만들지 않고도 기존 개체를 기반으로 새 개체를 만들 수 있습니다. 기본적으로 object()는 전달된 객체의 얕은 복사본을 수행합니다.
[참고] 프로토타입 상속에서는 다른 객체의 기반으로 사용할 수 있는 객체가 있어야 합니다. 그러한 객체가 있는 경우 이를 object() 함수에 전달한 다음 얻은 객체를 특정 항목에 따라 수정할 수 있습니다. 필요

function object(o){
  function F(){};
  F.prototype = o;
  return new F();
}
var person = {
  name: "Nicholas",
  friends: ["Shelby","Court","Van"]
};
var anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");

var yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");

alert(person.friends);//"Shelby,Court,Van,Rob,Barbie"

【4.1】【Object.create() 메서드】: ECMAScript5의 새로운 Object.create() 메서드는 프로토타입 상속을 표준화합니다. 이 메서드는 두 가지 매개 변수, 즉 새 개체의 프로토타입으로 사용할 개체와 (선택적으로) 새 개체에 대한 추가 속성을 정의하는 개체를 허용합니다. 매개변수가 전달되면 Object.create() 및 object() 메서드가 동일하게 동작합니다.

function object(o){
 function F(){};
 F.prototype = o;
 return new F();
}
var person = {
 name: "Nicholas",
 friends:["Shelby","Court","Van"]
};
var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
var yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
alert(person.friends);//"Shelby,Court,Van,Rob,Barbie"

[참고] Object.create() 메서드의 두 번째 매개 변수는 Object.defineProperties() 메서드의 두 번째 매개 변수와 동일한 형식을 갖습니다. 각 속성은 자체 설명자를 통해 정의됩니다. 이런 방식으로 지정된 모든 속성은 프로토타입 객체에 있는 동일한 이름의 속성을 재정의합니다.

var person = {
 name: "Nicholas",
 friends:["Shelby","Court","Van"]
};
var anotherPerson = Object.create(person,{
 name: {
  value: "Greg"
 }
});
alert(anotherPerson.name);//"Greg" 

【4.2】하위 버전 브라우저의 Object.create() 메소드와 호환

if(typeof Object.create != "function"){
 (function(){
  var F = function(){};
  Object.create = function(o){
   if(arguments.length > 1){
    throw Error('Second argument noe supported');
   }
   if(o === null){
    throw Error("Cannot set a null [[Prototype]]");
   }
   if(typeof o != 'Object'){
    throw TypeError("Arguments must be an object");
   }
   F.prototype = o;
   return new F();
  }
 })();
} 

5. [기생 상속] 상속 프로세스를 캡슐화하는 데만 사용되는 함수를 만듭니다. 이 함수는 내부적으로 객체를 향상시키고 마침내 모든 작업을 수행한 것처럼 보입니다. 같은 개체
[단점] 기능 재사용이 불가능

function object(o){
 function F(){};
 F.prototype = o;
 return new F();
}
function createAnother(original){
 var clone = object(original);//通过调用函数创建一个新对象
 clone.sayHi = function(){ //以某种方式来增强这个对象
  alert("hi");
 };
 return clone;//返回这个对象
}
var person = {
 name: "Nicholas",
 friends: ["Shelby","Court","Van"]
};
var anotherPerson = createAnother(person);
anotherPerson.sayHi();//"hi"

6. [기생 조합 상속] 생성자를 빌려 속성을 상속하고, 프로토타입 체인의 하이브리드 형태를 통해 메서드를 상속합니다. 이에 대한 기본 아이디어는 하위 유형의 프로토타입을 지정하기 위해 상위 유형의 생성자를 호출하는 대신 상위 유형의 프로토타입 복사본만 있으면 된다는 것입니다. 기본적으로 기생 상속을 사용하여 상위 유형의 프로토타입에서 상속한 다음 결과를 하위 유형의 프로토타입에 할당합니다. 기생 결합 상속은 참조 유형에 대한 가장 이상적인 상속 패러다임입니다.

//这个例子中的高效率体现在它只调用了一次Super构造函数,并且因此避免了在SubType.prototype上面创建不必要的、多余的属性。与此同时,原型链还能保持不变。
function object(o){
 function F(){};
 F.prototype = o;
 return new F();
}
function inheritPrototype(subType,superType){
 var prototype = object(superType.prototype);//创建对象
 prototype.constructor = subType;//增强对象
 subType.prototype = prototype;//指定对象
}
function SuperType(name){
 this.name = name;
 this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
 alert(this.name);
};
function SubType(name,age){
 SuperType.call(this,name);
 this.age = age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge = function(){
 alert(this.age);
}

이상은 이 글의 전체 내용이며, 자바스크립트에서 상속을 구현하는 방법입니다. 읽어주신 모든 분들께 감사드리며, 편집자는 앞으로도 열심히 노력하겠습니다!

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