在Javascript中对函数语句使用函数表达式有什么意义?

0 javascript function

我理解表达式在执行上下文到达之前不会"存在".我只是想知道是否有任何区域使用函数表达式比普通函数语句更好,您不必担心函数何时会被保存到内存中.

我完全了解它们如何在差异中工作,我只是对表达的用途感到好奇.

jfr*_*d00 5

函数表达式在以下几种情况下很有用

为属性分配函数时:

SomeClass.prototype.myMethod = function(args) {
    // implementation
}
Run Code Online (Sandbox Code Playgroud)

根据情况创建可能包含不同实现的变量时:

var sortFn;

if (high > low) {
    sortFn = function(...) {
        // sort increasing order
    }
} else {
    sortFn = function(...) {
        // sort decreasing order
    }
}

// some code that uses sortFn()
Run Code Online (Sandbox Code Playgroud)

在IIFE(立即调用的函数表达式)中:

var getUniqueID = (function() {
   var counter = 0;
   return function() {
       return counter++;
   }
})();

console.log(getUniqueID());   // 0
console.log(getUniqueID());   // 1
console.log(getUniqueID());   // 2
Run Code Online (Sandbox Code Playgroud)

关于IIFE的有用性还有许多其他参考:

Javascript为什么要在IIFE中包装变量或构造函数?

将整个Javascript文件包装在"(function(){...})()"之类的匿名函数中的目的是什么?

JavaScript中的(function(){})()构造是什么?

在javascript中自执行函数的目的是什么?

高级Javascript:为什么这个函数包含在括号中?

用于将函数作为参数传递的内联函数表达式:

fetch(someURL).then(function(value) {
    // this is inside a function expression
}).catch(function(err) {
    // handle errors here
});

myArray.forEach(function(item, index) {
    // process each item of the array here
    // in this function expression
});
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

89 次

最近记录:

9 年,2 月 前