gpt4 book ai didi

嵌套箭头函数的Javascript内存含义

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:21 26 4
gpt4 key购买 nike

考虑:

function f1() {
function n11() { .. lots of code .. };
const n12 = () => { .. lots of code .. };
return n11()+n12()+5;
}

const f2 = () => {
function n21() { .. lots of code .. };
const n22 = () => { .. lots of code .. };
return n21()+n22()+5;
}

我正在尝试了解调用 f1 和 f2 的内存含义。

关于 n11,this answer说:

For some very small and normally inconsequential value of "wasted".JavaScript engines are very efficient these days and can perform awide variety of tricks/optimizations. For instance, only thefunction-object (but not the actual function code!) needs to be"duplicated" internally. There is no "wasting" problem without anactual test-case that shows otherwise. This idiom (of nested andanonymous functions) is very common in JavaScript and verywell-optimized for.

但是我想知道这是否也适用于箭头函数(即 n12、n21 和 n22).. 开销是否只是上面的函数对象,或者整个嵌套函数代码是否会在每次 f1/f2 时重复叫什么?

谢谢!

最佳答案

在同一函数的不同闭包之间共享代码方面,绝对没有理由需要为箭头函数执行与传统函数不同的任何操作。箭头函数与传统函数的唯一区别在于,箭头函数保存的是 this 值。这可以使用为 Function.prototype.bind() 方法提供的相同机制来完成。箭头函数主要只是语法糖。

func = () => { body };

大致相当于:

func = function() { body }.bind(this);

(这是一个轻微的简化,因为箭头函数也没有得到 arguments 对象,但这不应该影响你的要求。)

关于嵌套箭头函数的Javascript内存含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46374343/

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