function makeGroup(param) {
this.group = param;
}
duplicateEmployee.makeGroup(index2);
做一个简单的duplicateEmployee.group = index2不起作用。尝试一种方法说" makeGroup不是一个函数。"
以下是完整的参考代码。
var someVar = [];
vm.contacts = ContactsService.query(employees => {
employees.forEach(employee => {
employee.groups.forEach((groupMembership, index2) => {
// getEmployee() works...
function getEmployee(param) {
return param;
}
// "makeGroup is not a function"
function makeGroup(param) {
this.group = param;
}
var duplicateEmployee = getEmployee(employee);
if (groupMembership) {
duplicateEmployee.makeGroup(index2); // this breaks it. Says makeGroup is not a function
console.log(groupMembership, index2); // index2 is working... that's the group number
someVar.push(duplicateEmployee);
}
});
});
});
vm.contacts = someVar;
试过这个并且它不起作用
function makeGroup(param1, param2) { // console.log(param2) === undefined
console.log(param1); // group number... not the employee (still useful)
console.log(this); // 'this' is the employee, so lets try this.group
this.group = param1; // still overwriting the variable
}
makeGroup.call(duplicateEmployee, index2)
答案 0 :(得分:2)
您正在调用makeGroup
对象的方法duplicateEmployee
。此对象中没有此方法。您可以将其添加到prototype
或只更改makeGroup
,这样它就是一个接收员工和参数的函数,它就是这样的。
function makeGroup(employee, param) {
employee.group = param;
}
getEmployee
的工作原因是因为您是从全局上下文调用它,而不是像duplicateEmployee
那样使用makeGroup
上下文调用它。
答案 1 :(得分:1)
duplicateEmployee.makeGroup(index2);
无法从员工处拨打,因为它不是该员工的成员。
您可以像makeGroup(index2)