javascript - Javascript 中的函数 foo(){} 和 foo: function(){} 有什么区别?
问题描述
所以我正在查看一段代码,我注意到了这一点:
clickNext: function(e) {
var cal = $(e.target).parents('.drp-calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add(1, 'month');
} else {
this.rightCalendar.month.add(1, 'month');
if (this.linkedCalendars)
this.leftCalendar.month.add(1, 'month');
}
this.updateCalendars();
},
这和这个是一回事吗?
function clickNext(e) {
var cal = $(e.target).parents('.drp-calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add(1, 'month');
} else {
this.rightCalendar.month.add(1, 'month');
if (this.linkedCalendars)
this.leftCalendar.month.add(1, 'month');
}
this.updateCalendars();
},
我以前没有见过那种函数声明,我很困惑,因为我尝试改变上面的下面并且代码停止工作。
解决方案
您可以通过两种方式编写函数:作为命名函数或作为具有匿名函数值的变量:
var fooBoo = function () {};
function fooBoo(){}
调用它是一样的:fooBoo()
。
从您的示例看来,您的对象具有具有功能的键之一:
var myObj = {
fooBar: function () {}
}
现在在这种情况下,您不能用它替换它,function fooBar(){}
因为它最终会出现错误的语法:
// NOT VALID!
var myObj = {
function fooBar() {}
}
推荐阅读
- angular - 如何在Angular的自定义控件组件中触摸内部控件?
- javascript - 由 onclick 事件触发时游戏卡在第一帧
- flutter - Flutter - 如何在不运行类似 CustomPainter 绘制方法的情况下移动和缩放 Canvas 绘图?
- python - 如何仅从 DataFrame 上的 groupby 中获取第一行?
- amazon-cloudformation - 通过 Cloudformation 创建的 CloudWatch 警报 OKActions 属性的值必须是字符串列表类型
- javascript - 组件确实更新但 if 语句不起作用
- c# - 如何有效地从 C# 中的流中获取 JSON 正文?
- microsoft-graph-api - 订阅是否有无限的生命周期?
- c# - 无法在 SQL Server 中使用 XML 节点遍历中的索引进行迭代
- python - Tkinter - 当我有不同类型的类时,如何正确使用“ttk.style()”语句?