我听说为匿名函数命名有助于调试。
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...*/}
最佳答案
是的。那里有同样的好处(and more)。
但是,引擎/调试器变得越来越智能,并且将通过它们所属的对象属性的键隐式命名函数。 ES6 甚至要求这样做(检查 .name
property )。但如果您使用 ES6,您可能会使用 method definition无论如何:-)
关于javascript - 在 JavaScript 中命名对象属性的方法是一个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008445/