在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,你可能会使用一个方法定义:-)
相关文章:
- 从我的控制器返回一个不同于200的代码以触发ajax错误,这被认为是一种好的做法吗
- 有没有一种好的方法可以为网页制作预览图像
- 在angular中使用$parent是一种好的做法吗
- 将CSS类用于逻辑是一种好的做法吗
- 在JavaScript中,从主线程和回调中调用函数是一种好的风格吗
- 使用jquery加载方法是一种好的做法吗
- 创建大量的js文件或者合并为一个文件是一种好的做法吗
- 这种减少if语句中声明的变量范围的模式是一种好的做法吗
- Dojo 1.9:在模板中将附着点标记为私有是否是一种好习惯
- 拥有胖$routeProviders和瘦控制器是否是一种好习惯
- 基于 html5 数据属性值创建 JavaScript 对象是否是一种好的做法
- 有没有一种好方法来识别一个单词,即使它在javascript中拼写错误
- 将所有脚本保存在一个文件中是否是一种好的做法
- 根据页面分隔JS文件是否是一种好的做法
- 有没有一种好方法可以添加新框并使用 javascript 重新绘制画布
- 在 javascript 中 for 循环的每次迭代中声明一个新的、唯一的变量是一种好方法
- 拥有基本服务是否有意义,如果是这样,这是一种好方法
- 使用 Javascript 创建侧边栏是一种好习惯吗?
- 在递归中使用全局变量是一种好的做法吗
- 在JavaScript中为对象属性的方法命名是一种好习惯吗?