// 声明一个对象const bug1 ={name:"Buggy McFly",phrase:"Your debugger doesn't work with me!"}const bug2 ={name:"Martiniano Buggland",phrase:"Can't touch this! Na na na na..."}// 这些函数将对象作为参数,并为对象添加方法constaddFlyingAbility=obj=>{
obj.fly=()=> console.log(`Now ${obj.name} can fly!`)}constaddSpeechAbility=obj=>{
obj.saySmthg=()=> console.log(`${obj.name} walks the walk and talks the talk!`)}// 最后传入对象作为参数,调用构造器函数addFlyingAbility(bug1)
bug1.fly()// 输出: "Now Buggy McFly can fly!"addSpeechAbility(bug2)
bug2.saySmthg()// 输出: "Martiniano Buggland walks the walk and talks the talk!"
4.原型模式
// 声明一个有两个方法的原型对象const enemy ={attack:()=> console.log("Pim Pam Pum!"),flyAway:()=> console.log("Flyyyy like an eagle!")}// 声明另外一个对象,这个对象将继承原型const bug1 ={name:"Buggy McFly",phrase:"Your debugger doesn't work with me!"}// 使用setPrototypeOf设置对象的原型
Object.setPrototypeOf(bug1, enemy)// 使用getPrototypeOf来确认我们是否设置成功
console.log(Object.getPrototypeOf(bug1))// { attack: [Function: attack], flyAway: [Function: flyAway] }
console.log(bug1.phrase)// Your debugger doesn't work with me!
console.log(bug1.attack())// Pim Pam Pum!
console.log(bug1.flyAway())// Flyyyy like an eagle!