JS中没有类(ES5),最早的js程序员是从Java转过来的,所以执着于类,所以想尽方法在js里实现类,所以在高程中会有寄生组合等实现方法。 但现在class和this是极度避免的事情如React的开发,但是面试会问。 方法一:使用原型
function Dog(name){
this.name = name
this.legsNumber = 4
}
Dog.prototype.kind = '狗'
Dog.prototype.say = fucnton(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
Dog.prototype.run = function(){
console.log(`${this.legsNumber}条腿跑起来。`)
}
const d1 = new Dog('哮天') //Dog函数就是一个类
d1.say()
方法二:使用class
class Dog{
kind = '狗' //等价于在constructor里写 this.kind = '狗'
constructor(name){
this.name = name
this.legsNumber = 4
// 思考:kind 放在哪,放在哪都无法实现上面的一样的效果
}
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
run(){
console.log(`${this.legsNumber}条腿跑起来。`)
}
}
const d1 = new Dog('啸天')
d1.say()