[英]array of objects and adding a function as a property and access other properties using this in typescript
I have an array of objects.我有一个对象数组。 I'm trying to not repeat my functions on every object.
我试图不在每个 object 上重复我的功能。
First, is the way I implemented my array of interface correct?首先,我实现接口数组的方式是否正确?
Second, how do I properly implement my function on each object?其次,如何在每个 object 上正确实现我的 function? Was not sure if I have to do a call or bind when I assign that function on each object.
当我在每个 object 上分配 function 时,不确定是否必须进行调用或绑定。 Or I am completely doing it wrong.
或者我完全做错了。
//interfaces
export interface IEmployee{
id: number;
name: string;
hourly: number;
hours_this_week: number;
paycheck: (() => number);
}
// my function
const calculatePayThisWeek = (): number => {
return this.hourly * this.hours_this_week;
}
export getEmployees = (): IEmployee[] => {
return [
{
id: 1,
name: 'John Doe',
hourly: 10,
hours_this_week: 5,
paycheck: calculatePayThisWeek
},
{
id: 2,
name: 'Jane Doe',
hourly: 15,
hours_this_week: 8,
paycheck: calculatePayThisWeek
}
]
}
You need calculatePayThisWeek
to be a function
, not an arrow function.您需要
calculatePayThisWeek
成为function
,而不是箭头 function。 Arrow functions capture the enclosing this
, which is not what you want.箭头函数捕获封闭的
this
,这不是您想要的。
You don't need to bind anything.你不需要绑定任何东西。 You should annotate
this
in calculatePayThisWeek
though.不过,您应该在
calculatePayThisWeek
中this
进行注释。
Full solution:完整解决方案:
interface IEmployee {
id: number;
name: string;
hourly: number;
hours_this_week: number;
paycheck: (() => number);
}
// my function
function calculatePayThisWeek(this: IEmployee): number {
return this.hourly * this.hours_this_week;
}
const getEmployees = (): IEmployee[] => {
return [
{
id: 1,
name: 'John Doe',
hourly: 10,
hours_this_week: 5,
paycheck: calculatePayThisWeek
},
{
id: 2,
name: 'Jane Doe',
hourly: 15,
hours_this_week: 8,
paycheck: calculatePayThisWeek
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.