georgej
georgej

Reputation: 3311

How to wrap constructor function in IIFE & place instance on Window object?

I want a file to attach a property to the Window object. This is the code I currently have

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();

I want to wrap this whole thing in an IIFE and place the binary instance as a property on the Window object (this will be a library and I don't want variable names to conflict). I have tried a couple of different times and get a max callstack error How would I do this correctly?

Upvotes: 0

Views: 394

Answers (1)

ilyaigpetrov
ilyaigpetrov

Reputation: 3883

Basically you do it this way:

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

Or this way with 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!

Upvotes: 1

Related Questions