Reputation: 845
function makeGroup(param) {
this.group = param;
}
duplicateEmployee.makeGroup(index2);
Doing a simple duplicateEmployee.group = index2 doesn't work. Trying a method says "makeGroup is not a function."
Here's the full code for reference.
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;
Tried this and it doesn't work
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)
Upvotes: 0
Views: 1142
Reputation: 1782
You're calling a method makeGroup
of a duplicateEmployee
object. This object does not have this method in it. You can either add it to its prototype
or just change makeGroup
so that it's a function that takes in the employee and the param, and it'd be something like so.
function makeGroup(employee, param) {
employee.group = param;
}
The reason getEmployee
works is because you're calling it from the global context, and not from a duplicateEmployee
context like you're doing with makeGroup
.
Upvotes: 2
Reputation: 5389
duplicateEmployee.makeGroup(index2);
can't be called from the employee because it's not a member of that.
You can just call it like that makeGroup(index2)
Upvotes: 1