简体   繁体   English

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

[英]Javascript memory implication of nested arrow functions

Consider: 考虑:

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;
}

I am trying to understand the memory implications of calling f1 and f2. 我试图理解调用f1和f2的内存含义。

Regarding n11, this answer says: 关于n11, 这个答案说:

For some very small and normally inconsequential value of "wasted". 对于一些非常小且通常无关紧要的“浪费”的价值。 JavaScript engines are very efficient these days and can perform a wide variety of tricks/optimizations. JavaScript引擎现在效率很高,可以执行各种技巧/优化。 For instance, only the function-object (but not the actual function code!) needs to be "duplicated" internally. 例如,只有函数对象(但不是实际的函数代码!)需要在内部“复制”。 There is no "wasting" problem without an actual test-case that shows otherwise. 没有显示其他情况的实际测试用例,没有“浪费”问题。 This idiom (of nested and anonymous functions) is very common in JavaScript and very well-optimized for. 这个成语(嵌套和匿名函数)在JavaScript中很常见,并且非常优化。

However I want to know if this also apply to arrow functions (ie n12, n21 and n22) .. will the overhead only be a function-object as above or will the entire nested function code be duplicated every time f1/f2 are called ? 但是我想知道这是否也适用于箭头函数(即n12,n21和n22)..开销只是如上所述的函数对象,还是每次调用f1 / f2时都会复制整个嵌套函数代码?

thx! 谢谢!

There's absolutely no reason why an implementaton would need to do anything different for arrow functions than traditional functions with regard to the sharing of code between different closures of the same function. 对于在同一函数的不同闭包之间共享代码而言,一个实现在箭头函数上需要做的事情与传统函数不同。 The only difference between arrow functions and traditional functions is that arrow functions save the this value. 箭头函数和传统函数之间的唯一区别是箭头函数保存this值。 This can be done using the same mechanism as is already provided for the Function.prototype.bind() method. 这可以使用与已为Function.prototype.bind()方法提供的机制相同的机制来完成。 An arrow function is mostly just syntactic sugar. 箭头函数大多只是语法糖。

func = () => { body };

is roughly equivalent to: 大致相当于:

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

(This is a slight simplification, since arrow functions also don't get an arguments object, but that shouldn't affect what you're asking.) (这是一个轻微的简化,因为箭头函数也没有获得arguments对象,但这不应该影响你所要求的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM