gpt4 book ai didi

javascript - 为什么我不需要调用运算符来调用 JavaScript 中的函数?

转载 作者:行者123 更新时间:2023-11-30 07:39:49 25 4
gpt4 key购买 nike

很简单,我现在想知道为什么有时您不需要调用运算符 () 来调用函数?

这是我通常做的:

function startUp() {
alert("started");
}

// and later...
startUp(); //to call it, this will actually trigger the alert

//If I do this
startUp; //It prints the function in the a Browser's console, but won't call the function

现在,如果我将函数附加到浏览器事件:

 <script>

function startUp() {
alert("started");
}

window.onload = startUp; //I don't need the () to call the Function! WHY is that??

</script>

正如我在评论中提到的,为什么我有时不需要() 来调用函数? (就像在这种情况下)

预先感谢您的解释。

最佳答案

window.onload = startUp;

这不是你调用函数。相反,您传递对函数的引用作为窗口的 onload 事件的处理程序。触发事件时,将调用与其关联的所有处理程序(即执行函数时)。

考虑以下代码:

function foo() {
console.log('I am fired');
}

function run(func){
func();
}

var bar = foo; // nothing is called on this line
run(bar); // bar is not called on this line. It is called in run().
run(foo); // same thing.

对于您的示例,window.onload = startUp,浏览器触发回调(与所有浏览器事件、超时回调等一样)。 startUp 函数将在页面内容(HTML、引用的 CSS、引用的图像等)加载后由浏览器调用。

另外值得注意的是,可以使用参数调用该函数。浏览器事件通常用 this 作为触发事件的元素(在本例中它应该是 window)调用它,第一个参数是被触发的事件。如果你想复制它,它看起来像这样:

function fireCallbacks(element,callbacks){
var event = new Event();
for (var i=0; i<callbacks.length; i++) {
callbacks[i].call(element, event);
}
}

fireCallbacks(window, [startUp]);

Function.prototype.call用于执行具有特定 this 值和参数的函数。

关于javascript - 为什么我不需要调用运算符来调用 JavaScript 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20499143/

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