Vitaminaq / interview-collection

前端面试合集
3 stars 0 forks source link

JS继承,请分别用ES5和ES6实现继承 #4

Open Vitaminaq opened 2 years ago

Vitaminaq commented 2 years ago
// es5
function Person() {
    this.hand = 2;
    this.leg = 2;

    this.eat = function() {
        console.log('I can eat');
    }
}
Person.prototype.say = function() {
    console.log('I can say');
}
// es6
class Person {
    constructor() {
        this.hand = 2;
        this.leg = 2;
    }

    eat() {
        console.log('I can eat');
    }
}
// 实现
const xiaoming = new XiaoMing();
xiaoming.hard; // 2
xiaoming.eat(); // I can eat
xiaoming.say(); // I can say
Vitaminaq commented 2 years ago
// es5 - 寄生组合式继承
function Person() {
    this.hand = 2;
    this.leg = 2;

    this.eat = function() {
        console.log('I can eat');
    }
}
Person.prototype.say = function() {
    console.log('I can say');
}

function XiaoMing() {
    Person.call(this);
}

XiaoMing.prototype = Object.create(Person.prototype);
XiaoMing.prototype.constructor = XiaoMing;

// es6
class XiaoMing extends Person {
    say() {
        console.log('I can say');
    }
}
GetHere commented 2 years ago
// es5
function XiaoMing() {
    Person.call(this);
}

XiaoMing.prototype = new Person();