I'm trying to become more familiar with callback functions in Javascript. I've created a simple app to push a new member to a development team array. I'm trying to use the addDev function as my callback practice. I'm receiving an error: Uncaught TypeError: addDev is not a function.
var devTeam = [];
function devMember(fName, lName, addDev){
this.firstName = fName;
this.lastName = lName;
this.fullName = firstName + " " + lastName;
addDev(fullName);
}
function addDev(member){
devTeam.push(member);
console.log(devTeam);
}
devMember('Jay', 'Spears');
1 Answer 1
That's because you never passed addDev to devMember.
Try devMember('Jay', 'Spears', addDev);
Even though addDev is defined (hoisted), because you're calling the third argument to devMember also addDev, you're overriding it. And then you don't pass anything as a third argument when you invoke devMember('Jay', 'Spears'), so it is undefined in the execution context of devMember.
6 Comments
addDev is global function, shouldn't it be called?addDev declaration in the function arguments shadows the global declaration, and the variable will be undefined if no third parameter is passed. The code would have worked without this third parameter.devMember, or even call it something else (either way, not recommended), it would work. The best thing is to call it something other than addDev, and then pass addDev as an argument when you invoke devMember.function devMember(fName, lName, pushMember){};addDev when you invoke devMember.
devMember()function takes 3 arguments.