方法一:使用原型(对象本身的属性写在构造函数里面,共有属性写在原型上面)
function Dog(name){
this.name = name
this.legsNumber = 4
}
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
Dog.prototype.run = function(){
console.log(`${this.legsNumber}条腿跑起来。`)
}
const d1 = new Dog('啸天') // Dog 函数就是一个类
d1.say()
请试着实现一个 Chicken 类,没 name 会 say 会 fly。
function Chicken(){
this.legsNumber = 2
this.wingsNumber = 2
}
Chicken.prototype.kind = '鸡'
Chicken.prototype.say = function(){
console.log(`咯咯咯~ 我有${this.legsNumber}条腿。`)
}
Chicken.prototype.fly = function(){
console.log(`${this.wingsNumber}个翅膀飞起来。`)
}
const c1 = new Chicken()
c1.say()
方法二:使用 class(将对象本身的属性写到 constructor 里面,共有属性写到 constructor 外面)
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()