如何实现类

98 阅读1分钟

用原型的方式实现类

  • 把不能共用的属性放到构造函数里面
  • 能共享的属性就放到prototype里面
function Duck(name,legs) {
    this.name = name;
    this.legs = legs;
}
​
Duck.prototype.say = function() {
    alert('嘎嘎嘎')
}
Duck.prototype.eyes = 2;
​
const smallDuck = new Duck('小黄',3)
​
smallDuck.say()
console.dir(smallDuck)

为什么我们在给prototype增加属性的时候,不用下面的方式?

Duck.prototype = {
    say() {alert('嘎嘎嘎')},
    eyes:2
}
  • 因为prototype会自带一个constructor属性,指向构造函数
  • 为了不影响它,还是单独写比较好

用class实现类

  • 不共享属性就放在constructor里面
  • 共享属性就放在constructor外面
class Chiken {
    //注意这里是=而不是:
    kind = 'animal';// 相当于放到constructor
    constructor(name,legs) {
        this.name = name;
        this.legs = legs
    }
    say() {
        alert('咯咯咯')
    }
}
const smallChiken = new Chiken('yellow',2)
smallChiken.say()
console.dir(smallChiken)

在ES5时代没有class,为什么要实现类?

  • 很多JAVA程序员习惯了JAVA有类