1、为对象定义方法
function registerEmployee(p:any){
return p
}
const emp1 = registerEmployee({
name:'james',
salary:10000,
bonus:undefined as (number | undefined),
performance:4.5,
//对象方法,当然this也有嵌套函数调用的深坑
updateBonus(){
if(!this.bonus){
this.bonus = this.salary * this.performance
}
},
})
// 执行对象方法
emp1.updateBonus()
console.log(emp1)
/* 输出结果:
{
"name": "james",
"salary": 10000,
"bonus": 45000,
"performance": 4.5
}
*/
这篇博客展示了如何为对象定义方法,通过`registerEmployee`函数创建了一个包含`updateBonus`方法的员工对象。当调用`updateBonus`方法时,它会根据员工的绩效更新奖金。例子中,员工的奖金被正确地计算并更新为45000。
1万+

被折叠的 条评论
为什么被折叠?



