Object Method Overloading
Function Overloading
by nickadeemus2002
JavaScript
/**
* JS function overloading
*/
// add object methods that will
// execute different logic based on
// the arguments passed to addMethod
function addMethod(obj, name, fn) {
var stored = obj[name];
obj[name] = function() {
if (fn.length === arguments.length) {
return fn.apply(this, arguments);
} else if (typeof stored === 'function') {
return stored.apply(this, arguments);
}
};
}
//create object
var students = {
honorRoll: [{
firstName: "Makayla",
lastName: "Villanueva"
}, {
firstName: "Kathryn",
lastName: "Villanueva"
}, {
firstName: "Chris",
lastName: "Villanueva"
}, {
firstName: "Cindy",
lastName: "Villanueva"
}]
};
// add a "get" method to students
// that returns different results determined
// by arguments passed to "get" method
//get all
addMethod(students, "get", function() {
return this.honorRoll;
});
//get by index
addMethod(students, "get", function(idx) {
return this.honorRoll[idx];
});
//get by name
addMethod(students, "get", function(firstName, lastName) {
return this.honorRoll.filter(function(student) {
if (student.firstName === firstName && student.lastName === lastName) {
return student;
}
});
});
console.log( "students.get()", students.get() );
console.log( "students.get(2)", students.get(2) );
console.log( "students.get('Makayla', 'Villanueva')", students.get('Makayla', 'Villanueva') );
console.log( "students.get('Kathryn', 'Villanueva')", students.get('Kathryn', 'Villanueva') );