【问题标题】:Refactor to avoid global leaks? (underscore js like pattern)重构以避免全局泄漏? (下划线js样模式)
【发布时间】:2013-12-21 11:51:51
【问题描述】:

我想模块化一些功能,我想使用下划线js之类的模式,但我总是收到全局泄漏警告。

// simple test use case
var decorate = require('../lib/decorate');
var expect = require('expect.js');

describe('decorate', function() {

  it('should wrap', function() {
    var arr = []
    expect( decorate('dummy').wrapWith(' oOo ') ).to.eql( ' oOo dummy oOo ' );
  });

});

现在它通过mocha --ignore-leaks 传递,但可以在没有全局泄漏的情况下包装它吗?

这是基本代码:

// decorate.js
(function () {
  // 'use strict'; // not yet

  function Decorate(obj) {
    this._obj = obj; // FIXME: global leaks _obj
    if (!(this instanceof Decorate)){
        return new Decorate(this._obj);
    }
  }

  Decorate.prototype.wrapWith = function(wrap) {
    return wrap + this._obj + wrap;
  }

  // export for node or the browser
  if (typeof module !== 'undefined') {
    module.exports = Decorate;
  } else {
    window.decorate = Decorate;
  }
}.call(this));

【问题讨论】:

    标签: javascript design-patterns refactoring scope mocha.js


    【解决方案1】:
      function Decorate(obj) {
        this._obj = obj; // FIXME: global leaks _obj
        if (!(this instanceof Decorate)){
            return new Decorate(this._obj);
        }
      }
    

    您有一些代码允许您在没有new 的情况下调用Decorate,即this 不是Decorate 实例。如果检测到这种情况,则会显式创建并返回一个新实例。

    但是,无论测试结果如何,您都在该测试之前创建了 ._obj 属性!需要在顶部进行测试,如果没有作为构造函数调用,则立即中止构造函数。

      function Decorate(obj) {
        if (!(this instanceof Decorate))
            return new Decorate(obj); // abort! abort!
    
        this._obj = obj; // Does not leak any more
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2012-06-28
      • 2023-03-23
      相关资源
      最近更新 更多