Benefits of using `Object.create` for inheritance

前端 未结 4 1139
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 05:43

I\'ve been trying to wrap my head around the new Object.create method which was introduced in ECMAScript 5.

Usually when I want to use inheritance I do

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 06:38

    Let's understand it with code only;

    A.prototype = B.prototype;

    function B() {console.log("I am B");this.b1= 30;}
        B.prototype.b2 = 40;
    
        function A() {console.log("I am A");this.a1= 10;}
        A.prototype.a2 = 20;
    
        A.prototype = B.prototype;
    
        A.prototype.constructor = A; 
    
        var a = new A;
        var b = new B;
    
        console.log(a);//A {a1: 10, b2: 40}
        console.log(b);//B {b1: 30, b2: 40}
    
        console.log(A.prototype.constructor);//A
        console.log(B.prototype.constructor);//A
        console.log(A.prototype);//A {b2: 40}
        console.log(B.prototype);//A {b2: 40}
        console.log(a.constructor === A); //true
        console.log(b.constructor === A); //true
    
    console.log(a.a2);//undefined
    

    enter image description here

    A.prototype = Object.create(B.prototype);

    function B() {console.log("I am B");this.b1= 30;}
    B.prototype.b2 = 40;
    
    function A() {console.log("I am A");this.a1= 10;}
    A.prototype.a2 = 20;
    
    A.prototype = Object.create(B.prototype);
    
    A.prototype.constructor = A; 
    
    var a = new A;
    var b = new B;
    
    console.log(a);//A {a1: 10, constructor: function, b2: 40}
    console.log(b);//B {b1: 30, b2: 40} 
    
    console.log(A.prototype.constructor);//A
    console.log(B.prototype.constructor);//B
    console.log(A.prototype);//A {constructor: function, b2: 40}
    console.log(B.prototype);//B {b2: 40}
    console.log(a.constructor === A); //true
    console.log(b.constructor === B); //true
    console.log(a.a2);//undefined
    

    enter image description here

提交回复
热议问题