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

时间:2016-10-12 21:12:55

标签: javascript function object anonymous-function

我听说过匿名函数的名称有助于调试。

JQuery的:

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

节点

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...*/
});

但是对象呢?

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...*/}

1 个答案:

答案 0 :(得分:4)

是。同样的好处(and more)。

但是,引擎/调试器变得越来越智能化,并且将通过它们所属的对象属性的键隐式命名该函数。 ES6甚至要求(检查.name property)。但是如果你使用ES6,你可能会使用method definition: - )