如何在IIFE&中包装构造函数在Window对象上放置实例?

时间:2017-05-16 14:49:49

标签: javascript constructor window iife

我想要一个文件将属性附加到Window对象。这是我目前的代码

function Binary() {
    var obj = function(msg){ console.log(msg + this.binaryString ) };
    obj.binaryString = ''

    Object.defineProperty(obj, 'zero', {
        get: function() {
            obj.binaryString += '0';
            return obj;
        }
    });

    ....

    return obj;
};

var binary = new Binary();

我想将整个事情包装在IIFE中并将binary实例作为属性放在Window对象上(这将是一个库,我不想要变量名称到冲突)。我尝试了几次不同的时间并得到max callstack error我该如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

基本上你是这样做的:

(function(){ /*Put code here.*/; window.binary = result; })()

或者return

'use strict';
window.binary = (function() {

  var obj = function(msg){ console.log(msg + this.binaryString ) };
  obj.binaryString = ''
  
  Object.defineProperty(obj, 'zero', {
    get: function() {
      obj.binaryString += '0';
      return obj;
    }
  });
  // ...
  return obj;

})();
console.log('1', window.binary);
console.log('2', binary);

/*
In modern JavaScript you may use `{...Code here...}` + `let`/`const`
as a scope, but it doesn't work for `var`s!
*/
'use strict'; // Don't forget strict mode!
{
  const foo = 42;
  let choo = 'Choo choo!';
  var goo = 55; // Leaks!

  function poo() { console.log('POO!'); }

  window.bar = 'baz';
}
console.log('foo', window.foo);   // undefined
console.log('choo', window.choo); // undefined
console.log('goo', window.goo);   // DEFINED!
console.log('poo', window.poo);   // undefined
console.log('bar', window.bar);   // DEFINED!