用原型的方式实现类
- 把不能共用的属性放到构造函数里面
- 能共享的属性就放到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实现类
class Chiken {
kind = 'animal';
constructor(name,legs) {
this.name = name;
this.legs = legs
}
say() {
alert('咯咯咯')
}
}
const smallChiken = new Chiken('yellow',2)
smallChiken.say()
console.dir(smallChiken)
在ES5时代没有class,为什么要实现类?