//一些补充
//在calss中无论是否通过constructor给对象绑定办法,都能够进行调用,他们的区别是:
// 在constructor中绑定的办法会被绑定在对象实例上
// 通过在constructor之外应用a(){}这种形式绑定的办法最终会被绑定在实例对象的 prototype 上
//首先申明一个calss对象
class Person{
id = '草根' //自带的数据
constructor(name, age){ //用于接管参数的数据源
this.name = name
this.age = age
}
say(){ //自带的办法
console.log(`我${this.name}是一个${this.age}岁的${this.id}`);
}
}
//通过对象合并的形式增加新的办法
Object.assign(Person.prototype,{
dreams(){
console.log(`即使我是${this.id},总有一天会成为这片海上最自在的人`);
}
})
//通过 prototype 的形式增加办法
Person.prototype.star = function(){
console.log(`让我的名字${this.name},响彻整个天下`);
}
//创建对象实例
let self = new Person('张嘀嗒',18)
//调用测试
self.say()
self.dreams()
self.star()
//测试class的继承 extends 继承只是继承外面的办法,数据不互通
class Other extends Person{
name = '大河川'
age = 66
sayToo(){
console.log(`俺${this.name}也是`);
}
}
let another = new Other()
another.say()
another.sayToo()
发表回复