繁体   English   中英

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

是。 同样的好处( 还有更多 )。

但是,引擎/调试器变得越来越智能,它们将通过它们所属的对象属性的键隐式命名该函数。 ES6甚至要求这样做(检查.name属性 )。 但是,如果您使用的是ES6,您可能还是会使用方法定义 :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM