1

我刚刚阅读了这篇文章http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/

在标题为“#4 添加缓存”的部分中,它说:

通过在 mixin 周围形成一个闭包,我们可以缓存初始定义运行的结果,并且性能影响非常显着。

我不明白这是如何工作的——在这里使用模块模式如何导致代码的更快/缓存版本?

4

3 回答 3

2

基本上,不使用闭包,每次使用 mixin 时都会创建 mixin 函数。通过创建闭包,每个函数都将创建一次,并且 mixin 将在每次调用时引用这些函数。由于 mixin 不必在每次运行时都重新创建这些函数,因此速度更快。

没有关闭

var asRectangle = function() {
  // every time this function is called, these three functions are created
  // from scratch, slowing down execution time
  this.area = function() {
    return this.length * this.width;
  }
  this.grow = function() {
    this.length++, this.width++;
  }
  this.shrink = function() {
    this.length--, this.width--;
  }
})();

关闭

var asRectangle = (function() {
  // these functions are 'cached' in the closure
  function area() {
    return this.length * this.width;
  }
  function grow() {
    this.length++, this.width++;
  }
  function shrink() {
    this.length--, this.width--;
  }

  // this function is set to asRectangle.  it references the above functions
  // every time it is called without having to create new ones
  return function() {
    this.area = area;
    this.grow = grow;
    this.shrink = shrink;
    return this;
  };
})();
于 2012-11-13T18:56:35.587 回答
1

这不是闭包或模块模式,而是它的结果:不同的构造函数/mixin 函数。尽管

function mixin() {
    this.method = function() { ... }
}

在每次调用时为方法创建新的闭包范围(的执行上下文mixin,不包含变量 - 但需要保留在内存中),

function method() { ... }
function mixin() {
    this.method = method;
}

只创建一个只存在于一个范围内的函数(多次应用时)。

模块模式仅用于制作method局部变量。

于 2012-11-13T19:22:37.713 回答
0

在第二种情况下,仅执行此代码:在应用 mixin 时:

this.area = area;
this.grow = grow;
this.shrink = shrink;
return this;

在第一种情况下 areagrowshrink为每个asXXX调用重新定义。在第二种情况下,方法及其缓存的定义是在 mixin 声明的“解析”时完成的,因此只需要完成一次。

于 2012-11-13T18:52:31.290 回答