在 JavaScript 中命名对象的 属性 的方法是一种好习惯吗?

Is it good practice to name a method of a objects property in 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...*/}

是的。那里有相同的好处 (and more)。

然而,engines/debuggers 变得越来越智能,并且会隐式地通过它们所属的对象 属性 的键来命名函数。 ES6 甚至要求(无论如何检查 .name property). But if you were using ES6, you'd probably be using a :-)