>  기사  >  웹 프론트엔드  >  Javascript_javascript 기술에서 상속을 구현하는 방법에 대한 간략한 토론

Javascript_javascript 기술에서 상속을 구현하는 방법에 대한 간략한 토론

WBOY
WBOY원래의
2016-05-16 15:51:311033검색

S1: js의 모든 것은 객체입니다. 초기에 상위 객체의 속성과 메서드 상속을 어떻게 구현할 것인지 생각해 보세요. 프로토타입의 개념을 고려하면 이것이 제가 처음에 상속을 구현한 방법입니다.

function Parent(){
   this.name='123';
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
console.log('Name :'+son.getName()+';Age: '+son.getAge());
 
 
VM1777:16 Name :123;Age: 20

위에서 볼 수 있듯이 Parent의 상속은 주로 Son의 프로토타입을 덮어쓰는 것이므로 Parent의 속성과 메서드가 Son의 프로토타입에 전달됩니다. 이러한 방식으로 새 Son을 통해 객체가 구성됩니다. ()는 모두 프로토타입(즉, 상위 개체 Parent)에서 속성과 메서드를 상속하므로 상속 효과를 얻을 수 있지만 이는 부모 개체에 참조 유형 특성이 포함된 경우 부작용이 발생합니다. 하위 개체는 참조 유형 데이터를 수정하고 모든 하위 개체에 영향을 미칩니다. 분명히 이것은 우리에게 필요한 효과가 아닙니다.

function Parent(){
   this.name='123';
   this.fruits=['apple'];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
var son1=new Son();
console.log(son.fruits);//["apple"]
console.log(son1.fruits);//["apple"]
son.fruits.push('pear');
console.log(son.fruits);//["apple", "pear"]
console.log(son1.fruits);//["apple", "pear"]

S2: 이 문제를 해결하기 위한 현재 생각은 각 하위 개체에 상위 개체 속성의 복사본을 갖도록 하는 것입니다. 이런 방식으로 속성을 수정할 때 속성에 영향을 주지 않고 하위 개체 아래의 속성만 수정됩니다. 다른 하위 개체의 . 이 목표는 이전 개체 가장 방법을 참조하여 달성됩니다

function Parent(){
   this.name='123';
   this.fruits=['apple'];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   Parent.call(this);
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
var son1=new Son();
console.log(son.fruits);//["apple"]
console.log(son1.fruits);//["apple"]
son.fruits.push('pear');
console.log(son.fruits);//["apple", "pear"]
console.log(son1.fruits);//["apple"]

위의 Son 함수에 Parent.call(this)을 추가하여 이 [새 Son 객체]가 new Son() 중에 Parent() 함수를 호출하는 Parent 함수의 컨텍스트 this인 것처럼 가장했습니다. 상위 개체의 속성과 메서드의 복사본을 얻었으므로 다음에 상위 개체의 속성과 메서드를 수정하면 실제로는 수정된 복사본이므로 모든 하위 개체에 영향을 주지 않는 효과를 얻습니다. 그러나 Son.prototype=new Parent()를 사용하면 두 인스턴스의 속성과 메서드를 얻을 수 있습니다. 복사본을 얻은 후에는 다음에서 볼 수 있듯이 부모 개체의 프로토타입만 필요합니다. 프로토타입만 필요합니다. getname();

S3: 다음 단계는 인스턴스의 속성과 메서드를 제거하는 것입니다. 이는 생성자가 작동하는 때입니다. Parent.prototype을 하위 개체의 프로토타입으로 네이티브 개체로 재구성합니다. . 그런 다음 생성자를 하위 생성자를 가리킵니다

function Parent(){
   this.name='123';
   this.fruits=['apple'];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   Parent.call(this);
   this.age=20;
}
function Extend(Parent,Son){
   var proto = new Object(Parent.prototype);
   proto.constructor = Son;
   Son.prototype=proto;
}
Extend(Parent,Son);
Son.prototype.getAge=function(){
   return this.age;
}

위 내용은 이 글의 전체 내용입니다. 모두 마음에 드셨으면 좋겠습니다.

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