Antonio Ortiz Antonio Ortiz - 1 month ago 5
Javascript Question

Is it good practice to name a method of a objects property in JavaScript?

I have heard having names for your anonymous functions helps with debugging.

JQuery:

$( "p" ).on( "click", function clickHndlr() {
/* body...*/
});


Node:

var EventEmitter = require('events').EventEmitter,
emitter = new events.EventEmitter();

emitter.on('customEvent', function customEventHndlr (message, status) {
/* body...*/
});


Vanilla JS:

button.addEventListener('keypress', function buttonHndlr() {
/* body...*/
});


But what about an object?

var starShipChecker = (function() {
var publicAPI = {
checkForWarpDrive : function(starShip){
if(!starShip.hasOwnProperty('warpDrive')) {
starShip.warpDrive = undefined;
console.log('Your star-ship, the ' + starShip.name + ', now has warp-drive!' +
'\n' + 'Use the addWarpDrive method to apply the maximum warp relevant to your ship Class...');
} else {
console.log('Your star-ship, the ' + starShip.name + ', has warp-drive already!' +
'\n' + 'But use the addWarpDriveMaxLevel method to apply the maximum warp relevant to your ship Class...');
}
},
addWarpDriveMaxLevel : function(){}
};
return publicAPI;

})();


Would you get the same benefit? Or is it different because they're methods?

checkForWarpDrive : function checkWarpDriveLikeYouWereScotty(starShip){ /* body...*/},
addWarpDriveMaxLevel : function addWarpDriveLikeYouWereScotty(){ /* body...*/}

Answer

Yes. Same benefits (and more) there.

However, engines/debuggers are getting increasingly more intelligent, and will implicitly name the function by the key of the object property they are part of. ES6 even requires that (check the .name property). But if you were using ES6, you'd probably be using a method definition anyway :-)