Home  >  Article  >  Web Front-end  >  JavaScript does not use prototype and new to implement inheritance mechanism_javascript tips

JavaScript does not use prototype and new to implement inheritance mechanism_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:23:471154browse

This method is not the author’s original creation. I just summarized it on the basis of my predecessors and came up with a simple and practical JavaScript inheritance method.

Traditional JavaScript inheritance is based on the prototype prototype chain, and requires the use of a large number of new operations. The code is not concise enough, the readability is not very strong, and it seems to be susceptible to prototype chain pollution.

The inheritance method summarized by the author is concise and clear. Although it is not the best method, I hope it can inspire readers.

Okay, no more nonsense, just look at the code, the comments are detailed, you can understand it at a glance~~~

Copy code The code is as follows:

 /**
* 14-11-11에 Yang Yuan이 작성했습니다.
* 프로토타입을 사용하지 않고 상속 구현
*
​*/
 /**
* 자바스크립트 객체 복사, 하나의 레이어만 복사되고 함수 속성만 복사되는데 이는 보편적이지 않습니다!
* @param obj 복사할 객체
* @returns 객체
​*/
 Object.prototype.clone = 함수(){
     var _s = 이것,
         newObj = {};
     _s.each(함수(키, 값){
         if(Object.prototype.toString.call(value) === "[객체 함수]"){
             newObj[키] = 값;
         }
     });
     newObj 반환;
 };
 /**
* obj의 모든 속성을 탐색하세요
*
* @param 콜백 콜백 함수. 콜백에는 키 속성 이름, 값 속성 값
이라는 두 가지 매개변수가 포함됩니다. ​*/
 Object.prototype.each = 함수(콜백){
     var 키 = "",
         _이것=이것;
     for (_this를 입력하세요){
         if(Object.prototype.hasOwnProperty.call(_this, key)){
             콜백(키, _this[키]);
         }
     }
 };
 /**
* 하위 클래스 생성
* @param ext obj에는 다시 작성하거나 확장해야 하는 메서드가 포함되어 있습니다.
* @returns 객체
​*/
 Object.prototype.extend = 함수(ext){
     var child = this.clone();
     ext.each(함수(키, 값){
         자식[키] = 값;
     });
     아이를 돌려보내세요;
 };
 /**
* 객체(인스턴스) 생성
* @param 인수는 생성자 매개변수 목록으로 임의 개수의 매개변수를 허용합니다
* @returns 객체
​*/
 Object.prototype.create = function(){
     var obj = this.clone();
     if(obj.construct){
         obj.construct.apply(obj, 인수);
     }
     obj 반환;
 };
 /**
* 사용예
* 번거로운 프로토타입과 새로운 것을 피하기 위해 이 상속 방법을 사용하십시오.
* 하지만 저자가 작성한 현재 예제에서는 부모 클래스의 기능(멤버 메서드로 이해 가능)만 상속할 수 있습니다.
* 더욱 풍부한 콘텐츠를 상속받고 싶다면 복제 방식을 개선해 주세요.
*
*
​*/
 /**
* 동물(부모클래스)
* @type {{construct: 구성하다, 먹다: 먹다}}
​*/
 var 동물 = {
     구성: 함수(이름){
         this.name = 이름;
     },
     먹다: function(){
         console.log("내 이름은 "this.name"입니다. 먹을 수 있어요!");
     }
 };
 /**
* 새(하위 카테고리)
* Birds는 상위 클래스의 eat 메소드를 재정의하고 fly 메소드를 확장합니다
* @type {하위 클래스|void}
​*/
 var Bird = Animal.extend({
     먹다: 기능(음식){
         console.log("내 이름은 " this.name "입니다. " 음식 "을 먹을 수 있어요!");
     },
     파리: 함수(){
         console.log("나는 날 수 있어요!");
     }
 });
 /**
* 새 인스턴스 생성
* @type {짐}
​*/
 var BirdJim = Bird.create("짐"),
     BirdTom = Bird.create("톰");
 BirdJim.eat("벌레");  //제 이름은 짐이에요. 벌레도 먹을 수 있어요!
 BirdJim.fly();  //날 수 있어요!
 BirdTom.eat("쌀");  //제 이름은 톰입니다. 밥 먹을 수 있어요!
 새Tom.fly();  //날 수 있어요!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn