我希望文件将属性附加到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如何正确执行此操作?

最佳答案

基本上,您可以这样进行:

(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!

09-19 06:32