我听说你的匿名函数的名字有助于调试。在JavaScript中命名对象属性的方法是一种好的做法吗?
JQuery的:
$("p").on("click", function clickHndlr() {
/* body...*/
});
节点:
var EventEmitter = require('events').EventEmitter,
emitter = new events.EventEmitter();
emitter.on('customEvent', function customEventHndlr (message, status) {
/* body...*/
});
香草JS:
button.addEventListener('keypress', function buttonHndlr() {
/* body...*/
});
但怎么样的对象呢?
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;
})();
你会得到同样的好处吗?或者它是不同的,因为它们是方法?
checkForWarpDrive : function checkWarpDriveLikeYouWereScotty(starShip){ /* body...*/},
addWarpDriveMaxLevel : function addWarpDriveLikeYouWereScotty(){ /* body...*/}
同样的事情。在查看堆栈跟踪时,如果您不指定名称,它很可能只会说'匿名函数'。无论您命名所有函数,以便您可以在堆栈跟踪中看到它们的名称取决于您。有些人会这样做,有些人不会。 –
那么,如果一个匿名函数有一个名字,它不再是匿名的,是吗? – Feathercrown
我想说,由于这些方法最终并不是匿名的,所以好处已经消失。 –