関数宣言をreturnステートメントの横に置くと、関数が巻き上げられなくなりますか?または、returnステートメント内に配置すると、関数式に変換されます。そのため、持ち上げられませんか?
// Hoisting doesn't work in here
function outer() {
console.log(inner); // Isn't hoisted
return function inner() {
console.log("hello world");
};
}
outer();
// Works in here
function outer() {
console.log(inner);
function inner() {
console.log("hello world");
}
return inner;
}
outer();
キーワードのfunction
直後に置くとreturn
、関数宣言ではなくなります。return
はその右側にのみ式を持つことができるため、関数式として解釈され、関数式は引き上げられません(またはその名前が変数として周囲のスコープに入れられます)。
これは特別なことではありませんreturn
。function
パーツを式として解釈するように強制する他のキーワードは、同じ効果があります。
function outer() {
console.log(typeof inner); // Isn't hoisted
if (function inner() {
console.log("hello world");
}) {
}
}
outer();
function outer() {
console.log(typeof inner); // Isn't hoisted
switch (function inner() { console.log("hello world"); }) {
}
}
outer();
function outer() {
console.log(typeof inner); // Isn't hoisted
const x = function inner() {
console.log("hello world");
};
}
outer();
関数が関数宣言として解釈されるためには(そして関数宣言が引き上げられる唯一の関数である)、function
演算子またはキーワードを介してコード内の他のステートメントに直接接続されていないスタンドアロンステートメントである必要があります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加