首页 > 解决方案 > 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();
},

我以前没有见过那种函数声明,我很困惑,因为我尝试改变上面的下面并且代码停止工作。

标签: javascript

解决方案


您可以通过两种方式编写函数:作为命名函数或作为具有匿名函数值的变量:

var fooBoo = function () {};
function fooBoo(){}

调用它是一样的:fooBoo()


从您的示例看来,您的对象具有具有功能的键之一:

var myObj = {
    fooBar: function () {}
}

现在在这种情况下,您不能用它替换它,function fooBar(){}因为它最终会出现错误的语法:

// NOT VALID!
var myObj = {
    function fooBar() {}
}

推荐阅读