Javascript 상속 메커니즘(자세한 답변, 그래픽 튜토리얼)

亚连
풀어 주다: 2018-05-19 10:50:40
원래의
1211명이 탐색했습니다.

JavaScript 상속은 많은 책에서 여러 유형과 구현 방법으로 신중하게 구분되어 있으며 일반적으로 객체 가장과 프로토타입 방법의 두 가지 유형이 있습니다. 이 두 가지 방법에는 각각의 장점과 단점이 있습니다. 먼저 여기에 나열한 다음 하위 수준에서 차이점을 분석하겠습니다. Javascript 클래스 및 객체 생성을 배운 후 이제 Javascript 상속 메커니즘의 구현을 요약하겠습니다. Javascript에는 Java와 같이 상속 메커니즘에 대한 엄격하고 명확한 정의가 없습니다. 상속 메커니즘의 구현을 "모방"하기 위해 자신만의 메소드를 설계할 수 있습니다. 여러 가지 방법이 있습니다:

1. 객체 가장

 <script type="text/javascript">
   function classA(str){
     this.str=str;
     this.printstr=function(){
       document.write(this.str);
       document.write("<br>");
     }
     this.getstr=function(){
       return this.str;
     }    
   }
   function classB(name,str){
     //下面这两句代码相当于将classA代码体中的内容搬到这里
     this.newMethod1=classA;
     this.newMethod1(str);
     //注意,这里的写法
     delete this.newMethod1;
     //新的方法和属性的定义须在删除了newMethod之后定义,因为可能覆盖超类的属性和方法。
     this.name=name;
     this.sayName=function(){
       document.write(this.name);
       document.write("<br>");
     }
     
   }
   var a=new classB("Amy","helloworld");
   a.printstr();
   alert(a.getstr());
   a.sayName();
 </script>
로그인 후 복사

함수로 정의된 코드 블록은 클래스와 동일하며 이 키워드를 사용하여 속성과 메서드를 추가할 수 있습니다. it , 위 코드에는 다음 두 문장이 있습니다.

this.newMethod1=classA;

this.newMethod1(str);


newMethod1 변수는 classB에 정의되어 있으며 classA와 classA를 가리키는 참조입니다. 이 두 줄의 코드는 여기서 classA 코드 블록의 내용을 직접 복사하는 것과 동일합니다. 이런 방식으로 생성된 classB 개체는 물론 classA의 속성과 메서드를 갖습니다. 객체 가장은 다음과 같이 다중 상속을 구현할 수도 있습니다.

function ClassZ() {
 this.newMethod = ClassX;
 this.newMethod();
 delete this.newMethod;

this.newMethod = ClassY;
 this.newMethod();
 delete this.newMethod;
}
로그인 후 복사

그러나 classY는 classX에서 동일한 이름의 속성과 메서드를 재정의합니다. 디자인에 문제가 없다면 classz는 다음과 같은 다른 클래스를 상속해서는 안 됩니다. 동일한 속성과 메서드.

2. call() 메소드를 사용하세요

 <script type="text/javascript">
   function classA(str){
     this.str=str;
     this.printstr=function(){
       document.write(this.str);
       document.write("<br>");
     }
     this.getstr=function(){
       return this.str;
     }    
   }
   function classB(name,str){
   //利用call方法实现继承
     classA.call(this,str);
     this.name=name;
     this.sayName=function(){
       document.write(this.name);
       document.write("<br>");
     }
     
   }
   var a=new classB("Amy","helloworld");
   a.printstr();
   alert(a.getstr());
   a.sayName();
 </script>
로그인 후 복사

call() 메소드의 첫 번째 매개변수는 객체를 전달하며, 다음 매개변수(여러 개가 있을 수 있음)는 객체를 참조합니다. call() 메소드를 호출하는 클래스(함수)에 필요한 매개변수를 제공하기 위해 classA.call()은 여기서 classA 코드 블록의 내용을 직접 복사하는 것과 동일합니다. classB의 객체도 직접 사용할 수 있습니다. classB의 변수와 메소드.

3. 프로토타입 체인

 <script type="text/javascript">
   function cA(){};
   cA.prototype.name="John";
   cA.prototype.sayName=function(){
     document.write(this.name);
     document.write("<br>");
   }
   function cB(){};
   cB.prototype=new cA();
   cB.prototype.age=23;
   cB.prototype.sayAge=function(){
     document.write(this.age);
     document.write("<br>");
   }
   var objB=new cB();
   objB.sayAge();
   objB.sayName();
   document.write("is objB the instance of cA "+(objB instanceof cA));
   document.write("<br>");
   document.write("is objB the instance of cB "+(objB instanceof cB));
   document.write("<br>");
 </script>
로그인 후 복사

여기서 클래스를 정의하는 데 사용됩니다. 함수는 매개변수 없이 정의됩니다. 모든 개체에 속하므로 여기에는 특별한 기능이 있습니다: cB.prototype=new cA(); 이 문장은 cA 개체의 내용을 cB에 복사하는 것과 동일하며 cB는 자체 속성과 메서드를 추가할 수도 있습니다.

4. 혼합 메소드

 <script type="text/javascript">
   function cA(name){
     this.name=name;
   };
   cA.prototype.sayName=function(){
     document.write(this.name);
     document.write("<br>");
   }
   function cB(name,age){
     cA.call(this,name);
     this.age=age;
   };
   cB.prototype=new cA();
   cB.prototype.sayAge=function(){
     document.write(this.age);
     document.write("<br>");
   }
   var objB=new cB("Alan",27);
   objB.sayName();
   objB.sayAge();
   document.write("is objB the instance of cA "+(objB instanceof cA));
   document.write("<br>");
   document.write("is objB the instance of cB "+(objB instanceof cB));
   document.write("<br>");
 </script>
로그인 후 복사

여기서는 클래스 본문에 속성을 캡슐화할 수 있으며, 프로토타입을 사용하여 메소드를 정의하는 것이 개인적으로 좋은 디자인 방법이라고 생각합니다. 여러 함수에 사용됩니다. 여기서는 두 가지 사항에 유의해야 합니다. cB 클래스 본문에 동시에 cA.call(this,name)이 있고 cB 프로토타입이 cB 개체에 할당되어야 합니다. is: cB.prototype=new cA(); cA.call(this, name)은 여기에서 cA 클래스 블록의 코드를 복사하는 것과 동일합니다. 동시에 cB에 메서드를 추가합니다. 자체 속성과 메서드를 추가할 수도 있습니다.

위 내용은 제가 여러분을 위해 정리한 내용입니다. 앞으로 도움이 되길 바랍니다.

관련 기사:

Servlet3.0 및 JS를 통한 Ajax 상호 작용 예제 자세한 설명


네이티브 JS 캡슐화 페이드인 및 페이드아웃 효과 기능의 단계에 대한 자세한 설명


p5.

js키보드 상호작용 기능 요약

위 내용은 Javascript 상속 메커니즘(자세한 답변, 그래픽 튜토리얼)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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