gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:46:57 27 4
gpt4 key购买 nike

这是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com