开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 9 天,点击查看活动详情
什么是时间死区?
Temporal Dead Zone 是 JavaScript 中的一种行为,当使用 let 和 const 关键字而不是 var 声明变量时会发生这种行为。在 ECMAScript 6 中,在其声明之前(在其范围内)访问letor变量会导致 ReferenceError。const发生这种情况的时间跨度,即从创建变量绑定到声明变量之间的时间跨度,称为临时死区。
让我们用一个例子来看看这个行为,
function somemethod() {
console.log(counter1); // undefined
console.log(counter2); // ReferenceError
var counter1 = 1;
let counter2 = 2;
}
什么是IIFE(立即调用函数表达式)?
IIFE (Immediately Invoked Function Expression) 是一个 JavaScript 函数,一旦定义就立即运行。它的签名如下所示,
(function () {
// logic here
})();
使用 IIFE 的主要原因是为了获得数据隐私,因为在 IIFE 中声明的任何变量都不能被外界访问。即,如果您尝试使用 IIFE 访问变量,则会抛出如下错误,
(function () {
var message = "IIFE";
console.log(message);
})();
console.log(message); //Error: message is not defined
什么是记忆化?
记忆化是一种编程技术,它试图通过缓存先前计算的结果来提高函数的性能。每次调用记忆函数时,其参数都用于索引缓存。如果数据存在,则可以返回它,而无需执行整个函数。否则执行该函数,然后将结果添加到缓存中。让我们举一个使用记忆添加功能的例子,
const memoizAddition = () => {
let cache = {};
return (value) => {
if (value in cache) {
console.log("Fetching from cache");
return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
} else {
console.log("Calculating result");
let result = value + 20;
cache[value] = result;
return result;
}
};
};
// returned function from memoizAddition
const addition = memoizAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached
什么是吊装?
提升是一种 JavaScript 机制,其中变量、函数声明和类在代码执行之前被移动到它们作用域的顶部。请记住,JavaScript 只提升声明,而不是初始化。我们举一个简单的变量提升的例子,
console.log(message); //output : undefined
var message = "The variable Has been hoisted";
上面的代码在解释器看来如下所示,
var message;
console.log(message);
message = "The variable Has been hoisted";
以同样的方式,函数声明也被提升
message("Good morning"); //Good morning
function message(name) {
console.log(name);
}
这种提升使得函数在声明之前可以在代码中安全地使用。