javascript - 为什么JavaScript函数调用中没有(){括号}

标签 javascript cordova phonegap-build

这是 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);

关于javascript - 为什么JavaScript函数调用中没有(){括号},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38518801/

相关文章:

php - 在页面的不同部分回显相同的 MySql 查询

javascript - 使用 javascript/jQuery 刷新特定 div 内容

cordova - ionic / Cordova /Phonegap : Is there a way to disable Emoji-Keyboard on iOS and Android?

javascript - 如何在 android phonegap 中将 Canvas 图像保存到设备的 sdcard 中?

javascript - 如何在 JavaScript 中限制追加字符串?

javascript - 单个 div 上的多个 onclick 事件 - 更改 div 边框颜色 - javascript

javascript - 从 Rails 助手调用 JS 函数

javascript - 高度不会一直过渡

android - 使用 Meteor 定位特定版本的 Android

javascript - 是否可以在不重新部署的情况下更新 PhoneGap 应用程序中的 HTML/CSS/JS 文件?