8 종류 JS 프로토 타입 상속 강제 인터뷰 전면 접근

JS 상속은 무엇인가?

정의

        클래스와 속성을 재사용하거나 다른 클래스 메소드 할 수 있습니다 경우에는 상속이라고합니다.

        대부분의 객체 지향 언어는 상속을 지원합니다.

특징 : 

       서브 클래스는 상위 클래스의 모든 기능을 사용할 수 있으며, 이러한 기능을 확장 할 수 있습니다.

       상속의 가장 중요한 장점은 코드 재사용, 대규모 소프트웨어 시스템을 구축하는 것입니다.

프로토 타입 체인은 상속 (전통 양식)

단점 : 

        과도한 쓸모의 속성을 상속

Grand.prototype.lastName = 'chen'
function Grand() {}
var grand = new Grand();
Father.prototype = grand;
function Father() {    
    this.name = 'hehe';
}
var father = new Father();
Son.prototype = father;
function Son() {}
var son = new Son();

复制代码

차입 생성자 (공식 상속 클래스)

장점 :

        당신은 매개 변수를 전달할 수 있습니다

단점 :

        당신은 차용 생성자의 프로토 타입을 상속 할 수 없습니다

        모든 생성자는 멀티 기능을한다 

function Person(name, age, sex) { 
    this.name = name;
    this.age = age;
    this.sex = sex;
}
function Student(name, age, sex, grade) {
    Person.call(this, name, age, sex);
    this.grade = grade;
}
var student = new Student('hehe', 40, 'male', 18);复制代码

결합 연속 (프로토 타입 상속 체인 속성 및 인스턴스의 생성자 빌린 사용 방법 프로토 타입 상속 속성 인기있는 용어)

장점 :

        자신의 장점 자바 스크립트 상속의 가장 일반적인 모드가되었다 융합 체인 및 프로토 타입 생성자 결함을 피

단점 :

        두 속성은 같은 인스턴스 및 프로토 타입에 존재    

Father.prototype.getfaName = function() {  
    console.log(this.faName);
}
function Father(name) {    
    this.faName = 'father';
}
Child.prototype = new Father();
Child.prototype.constructor = Child;
function Child(args) {    
    this.chName = 'child';
    Father.apply(this, []);
}
var child = new Child(); 复制代码

프로토 타입 상속    

단점 :

        당신은 자신의 프로토 타입을 변경할 수 없습니다

function create(o){
    function F(){};
    F.prototype = o; 
    return new F();        
}        
var Person = {
    name:'me',            
    hobbies:['riding', 'swimming']  
}
var anotherPerson = create(Person);
var anotherPerson2 = create(Person);
anotherPerson.name = 'her';
anotherPerson.hobbies.push('dancing');        
console.log(anotherPerson2.name, anotherPerson2.hobbies); // her ["riding", "swimming", "dancing"]复制代码

기생 상속

단점 :

        빌린 생성자 패턴으로 객체를 만들 때마다 다시 방법을 생성됩니다.

function createObj(o){   
    let clone = Object.create(o);            
    clone.sayName = function(){ 
        console.log('hi');            
    }
    return clone        
}        
let person = {            
    name:"JoseyDong",            
    hobbies:["sing","dance","rap"]        
}        
let anotherPerson = createObj(person);        
anotherPerson.sayName(); // => hi复制代码

성배 모드 (기생 상속의 조합)  

// 第一种写法
function inherit(Target, Origin) {   
    // 使用F空函数当子类和父类的媒介 是为了防止修改子类的原型对象影响到父类的原型对象 
    function F() {}
    F.prototype = Origin.prototype;
    Target.prototype = new F(); 
    Target.prototype.constructor = Target; // 防止new的时候 返回实例的构造函数指向混乱  
    Target.prototype.uber = Origin.prototype; // 寻找继承的原型是谁
}

// 第二种写法 采用立即执行函数和闭包的形式
var inherit = (function() {
    function F() {}    
    return function(Target, Origin) {   
        F.prototype = Origin.prototype;
        Target.prototype = new F(); 
        Target.prototype.contructor = Target; 
        Target.prototype.uber = Origin.prototype;
    }
})()复制代码

객체 매스커레이딩

단점 :

         그러나이 객체 포즈 문제는, 같은, 속성은 이전에 정의 된 바와 같이, 따라서 부모 클래스를 지원하는 객체 포즈 방법은 속성 범위가 아닌 같은 상황이 더 합리적이다 나중에 정의 할 때 상위 클래스의 속성.

         모든 생성자는 멀티 기능을한다

function Father(color) {        
    this.color = color;        
    this.showColor = function () {            
        alert(this.color);        
    }    
}    
function Father1(color) {        
    this.color1 = color;        
    this.showColor1 = function () {            
        alert(this.color1);        
    }    
}    
function Child(color, color1) {        
    this.Method = Father;        
    this.Method(color);        
    delete this.Method;        
    
    this.Method = Father1;        
    this.Method(color1);        
    delete this.Method;    
}    
var child = new Child("wu", "zhao");    
child.showColor();复制代码

ES6 문구는 상속을 확장

class Plane {    
    static alive() {        
        return true;    
    }    
    constructor(name) {        
        this.name = name || '普通飞机';        
        this.blood = 100;    
    }    
    fly() {        
        console.log('fly');    
    }
};
class AttackPlane extends Plane{    
    constructor(name) {        
        super(name);        
        this.logo = 'duyi';    
    }    
    dan() {        
        console.log('bububu');    
    }
}
var oAp = new AttackPlane('攻击机');
console.log(oAp);复制代码

참고 : 

        서브 클래스는 새로운 인스턴스를 생성 할 때, 그렇지 않으면 오류가 발생하지, 생성자 메서드의 슈퍼 메서드를 호출해야합니다. 서브 클래스가이 객체를 소유하고 있지 않기 때문이지만,이 객체는 슈퍼 메소드를 호출하지 않는 경우, 서브 클래스가이 객체를받지 않습니다, 그것을 처리하기 전에, 부모 클래스를 상속합니다. 따라서, 슈퍼를 호출 한 후에 만,이 키워드를 사용할 수 있습니다.

요약 ES5 ES6 사이의 차이를 상속?

상속 메커니즘의 ES5의 본질은 다음이 서브 클래스의 객체 인스턴스를 만들 수 위의이 부모 클래스에 추가하는 것입니다 (Parent.call (이)).

상속 메커니즘의 ES6의 본질은, (먼저 슈퍼 () 메서드를 호출해야합니다)이 부모 클래스의 객체 인스턴스를 생성 생성자 서브 클래스는이 수정 사용하는 것입니다.

당신의 칭찬은 그들이 어떤 응답 메시지 아래에서 서로 문제를 가지고 배울 수 있도록 희망의 연속 출력 전력의 내 포인트입니다 


HTTPS : //juejin.im/post/5ceca322f265da1bd6058416 재현

추천

출처blog.csdn.net/weixin_33933118/article/details/91463018