Search code examples
javascriptcordovaphonegap-build

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


This is a code snap of index.js file which is created by default in a new phonegap project.

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);
    }
};

On line 11,

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

I assume that this.onDeviceReady is a function call so why there is no () like this.onDeviceReady() here?


Solution

  • this.onDeviceReady is function reference here. When used () on function, it'll be called immediately.

    When used function reference the function is passed to the other function and when some event occurs the function is called.

    This is same as

    function somefun(callback) {
    
    
        // When something ASYNCHRONOUS process completes, call the callback function
        callback();
    }
    
    var myFun = function() {
        console.log('in myFun');
    };
    
    function somefun(myFun);