简单来说是的,
官方介绍
官方的函数调用简介:
JavaScript 函数内部的代码会在“某物”调用它时执行。
调用 JavaScript 函数
在函数被定义时,函数内部的代码不会执行。
在函数被调用时,函数内部的代码会被执行。
调用函数通常也可以说“启动函数”或“执行函数”。
加不加括号区别
函数加括号和不加括号的区别在于:
- 加括号表示立即执行。是函数调用
- 而不加括号则一般是在触发某个事件才执行。是函数引用
1.立即执行
function fnA(){
let a = 1
console.log(a)
}
function fnB(){
let b = 2
console.log(b)
}
fnA //网页window对象引用fn函数,不立即执行
fnB() //网页Windows对象调用fn函数,立即执行。输出b
2.形式不同
function fn(){
let a = 1
return a
}
//不加括号
const test1 = fn
/*相当于:
const test1 = function fn(){
let a = 1
return a
}
*/
//加括号
const test2 = fn()
/*相当于:
const test2 = function fn(){
let a = 1
return a
}()
*/
console.log("这里是test1:" + test1) //输出函数对象fn
console.log("这里是test2:" + test2) //输出1
3.本质区别
- 函数引用(不带括号):多变量引用同一函数fn时,变量在内存栈中存储的都是相同的地址,该地址指向内存堆中存储的fn。所以多个变量引用同一函数它们都是相等的,因为它们地址一样;
- 函数调用(带括号):多变量调用同一函数时,每次调用都会在内存被分配新的地址。所以它们是不同的。但注意,如果是非闭包写法调用函数(或非实例化调用函数)是会相等的,因为它比较的是值,不是内存地址。
function fn1(){
let a = 1
return a
}
const test1 = fn1
const test2 = fn1
if(test1 === test2){
console.log("函数引用相等") //输出
}else{
console.log("函数引用不相等");
}
const test3 = fn1()
const test4 = fn1()
if(test3 === test4){
console.log("值相等") //输出
}else{
console.log("值不相等");
}
const test5 = new fn1()
const test6 = new fn1()
if(test5 == test6){
console.log("实例化下相等")
}else{
console.log("实例化下不相等"); //输出
}
function fn2(){
let a = 1
return function(){
return a
}
}
const test7 = fn2()
const test8 = fn2()
if(test7 === test8){
console.log("函数调用相等")
}else{
console.log("函数调用不相等"); //输出
}
参考: JavaScript中的引用函数、调用函数和回调函数_庭一的博客-优快云博客_js 如何获取回调函数引用
总结
加括号是函数调用,不加括号是函数引用,它们是不同的。