devStandard/docs/learning/3-js/2.5-ES6的Class类和构造函数.md
2025-03-29 14:35:49 +08:00

1.5 KiB
Raw Blame History

ES6的Class和普通构造函数对比

https://zhuanlan.zhihu.com/p/42409367

JS构造函数

function MathHandle(x,y) {
    this.x = x;
    this.y = y;
}

MathHandle.prototype.add = function() {
    return this.x + this.y;
}
var m = new MathHandle(1,2);
console.log(m.add());

Class

//ES6的语法糖本质还是JavaScript面向对象那套东西。最终还是会转换成上面的代码
//形式上强行模仿了java,c#,有点失去了JavaScript的个性
class MathHandle {
    constructor(x,y) {
        this.x = x;
        this.y = y;
    }

    add() {
        return this.x + this.y;
    }
}
const m = new MathHandle(1,2);
console.log(m.add());

console.log(typeof MathHandle) // 'function'
console.log(MathHandle.prototype.constructor === MathHandle) //true
//构造函数的显式原型对象等于实例的隐式原型对象
console.log(m.__proto__ === MathHandle.prototype) // true

原生继承

function Animal() {
    this.eat = function() {
        console.log('animal eat')
    }
}
function Dog() {
    this.break = function() {
        console.log('dog bark');
    }
}
Dog.prototype = new Animal();
//哈士奇
var hashiqi = new Dog();
hashiqi.bark();
hashiqi.eat();

Class继承

class Animal {
    constructor(name) {
        this.name = name;
    }
    eat() {
        console.log(this.name + 'eat');
    }
}
class Dog extends Animal {
    constructor(name) {
        super(name);
    }
    say() {
        console.log(this.name + 'say');
    }
}
const dog = new Dog('哈士奇');
dog.say();
dog.eat();