简体   繁体   English

Crockford的实体化方法 - 为什么关闭?

[英]Crockford's entityify method -why the closure?

On page 90 of Crockford's JavaScript: The Good Parts, he has code has the following: 在Crockford的JavaScript:The Good Parts的第90页,他的代码有以下内容:

String.method('entityify', function(){

  var character = {
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
    '"': '&quot;'
  };

  return function(){
    return this.replace(/[<>&"]/g, function(c){
      return character[c];
    });
  };
}());

console.log("<&>".entityify());

Is there a good reason for the closure and immediately invoked outer function? 是否有充分的理由关闭并立即调用外部函数? The following seems to work just as well: 以下似乎也适用:

String.method('entityify', function(){

  var character = {
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
    '"': '&quot;'
  };

  return this.replace(/[<>&"]/g, function(c){
    return character[c];
  });
});

By doing it the way he did, he creates the character object once and reuses it. 通过这样做,他创建了一次 character对象并重复使用它。 With your edit, you recreate it every time. 通过编辑,您每次都可以重新创建它。 You could argue it either way, but that's the difference. 你可以用任何一种方式来论证,但这就是区别。 His uses fractionally more memory. 他的使用略高于内存。 Yours takes fractionally longer per call (maybe, depends on whether creating the object takes longer than the extra scope traversal step his has; it probably does, though). 你需要每次通话分数长(也许,取决于是否创建该对象不是额外的范围遍历步骤的他已经花费更长的时间,它可能确实,虽然)。 In neither case is it likely to be anything that you'd notice in the real world. 在任何情况下,它都不可能是你在现实世界中注意到的任何东西。

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

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