wangsiyuan0215 / blog

Personal blog as F2E for recoding issues in my jobs and harvest in my daily life.
5 stars 0 forks source link

论关于在 ES6 的 class 使用箭头函数方式的区别以及继承与 ES5 组合寄生式继承的区别 #5

Open wangsiyuan0215 opened 5 years ago

wangsiyuan0215 commented 5 years ago
/*

    关于箭头函数 和 ES6 的继承与 ES5 组合寄生式继承的区别

 */

class A {
    constructor () {
        this.handleClickB = this.handleClickB.bind(this);
    }
    handleClickA = () => {
        console.log('handleClickA');
    }
    handleClickB () {
        console.log('handleClickB');
    }
}

var a = new A();
console.dir(A);
console.dir(a);

a.handleClickA();
a.handleClickB();

class B extends A {
    handleTriggerA = () => {
        console.log('handleTriggerA');
    }
    handleTriggerB () {
        console.log('handleTriggerB');
    }

    static staticHandlerTriggerC () {
        console.log('staticHandlerTriggerC');
    }
}

var b = new B();
console.dir(B);
console.dir(b);

b.handleClickA();
b.handleClickB();

// ============== 经过 babel 转换之后的原型链 ===============

console.log(A.__proto__ === Function.prototype);
console.log(a.__proto__ === A.prototype);

// F.prototype = A.prototype;
// B.prototype = new F();
// B.prototype.__proto__ = F.prototype;
// B.prototype.__proto__ = F.prototype = A.prototype;
// B.prototype.constructor = F
// B.prototype = F

console.log(B.prototype.__proto__ === A.prototype);
// B.__proto__ === A 之所以成立,是因为
// babel 在执行继承后,会手动的将 B.__proto__ 改成父类 A
// 查看如下代码:
/*
function _setPrototypeOf(o, p) {
    _setPrototypeOf =
        Object.setPrototypeOf ||
            function _setPrototypeOf(o, p) {
                o.__proto__ = p;
                return o;
            };
     return _setPrototypeOf(o, p);
}
*/
console.log(B.__proto__ === A);

// ============== ES5 经典组合寄生式继承后的原型链 ===============

function AA () {
    this.m = function () {
        console.log('m');
    }
}

AA.prototype.p = function () {
  console.log('p1');
}

function BB () {
    AA.call(this);
}

function F () {}

F.prototype = AA.prototype;
BB.prototype = new F();
BB.prototype.constructor = BB;

var aa = new AA();
var bb = new BB();

console.warn('=============================================');
console.dir(BB);
console.log(BB.prototype.__proto__ === AA.prototype);
console.log(BB.prototype.constructor === BB);
console.log(BB.prototype.constructor.prototype === BB.prototype);
// 在创建 BB 时,BB.__proto__ 默认指向构建 BB 的构造函数 Function
// 这是因为没有改变 BB 的 __proto__
// 仅仅手动改变了 BB.prototype.constructor 的指向
console.log(BB.__proto__ === Function.protype);