为什么 JavaScript 函数调用中没有 () {parantheses}

Why there is not () {parantheses} in JavaScript function calling

这是 index.js 文件的代码快照,它是在新的 phonegap 项目中默认创建的。

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

第 11 行,

document.addEventListener('deviceready', this.onDeviceReady, false);

我假设 this.onDeviceReady 是一个函数调用,那么为什么这里没有像 this.onDeviceReady() 这样的 ()

this.onDeviceReady 是这里的函数引用。在函数上使用 () 时,会立即调用。

当使用函数引用时,函数被传递给另一个函数,当某些事件发生时,函数被调用。

这与

相同
function somefun(callback) {


    // When something ASYNCHRONOUS process completes, call the callback function
    callback();
}

var myFun = function() {
    console.log('in myFun');
};

function somefun(myFun);

如果我们在将函数作为引用传递时将 () 与 this.onDeviceReady 一起使用,将立即调用 onDeviceReady() 方法。