HypeWolf
HypeWolf

Reputation: 850

How to create or extend a global object

I'm trying to extend an object from an external JS file that is loaded into a page that may have the same object name present.

I already have an object in the global scope:

window.Qo = {}
window.Qo.myvar = 1

I need to include a JS file that will extend this if it does exists, or create it if not.

  (function(Qo) {
    Qo.prototype.var2 = 2

    function secretFn(value) {
      return value
    }

    Qo.prototype.public = function(value) {
      console.log(value)
      return value
    }
    return Qo
  })(window.Qo = window.Qo || {})

The last line, as I understands it, is that the object past to the function is window.Qo if it exists, or an empty object if not.

But trying to expend the original object, I get errors that the value is not a function, even if I pass a function to myvar.

TypeError: (intermediate value)(...) is not a function.

What am I missing here?

Also, is there something else to check when including global object on unknown/untrusted third-party website?

EDIT

I made a code based on the answers below:

  ;(function(Qo) {
      // Private variable
      var _bar;

      // Private function
      function _atob(value) {
        if(!typeof value === 'undefined')
        return atob(value)
      }
      // Public functions
      Qo.prototype.getBar = function() {
          return _bar;
      };
      Qo.prototype.setBar = function(bar) {
          _bar = bar;
      };

      return Qo;
  })(window.Qo = window.Qo || {})

  Qo.setBar('test')

Error: TypeError: Qo.prototype is undefined; can't access its "getBar" property

Upvotes: 0

Views: 111

Answers (2)

Monic Sitta
Monic Sitta

Reputation: 31

Probably you need to put a semicolon right before the code you posted. Since

whateverPrecedingExpression
(function(Qo) {
    Qo.prototype.var2 = 2

    function secretFn(value) {
      return value
    }

    Qo.prototype.public = function(value) {
      console.log(value)
      return value
    }
    return Qo
  })(window.Qo = window.Qo || {})

js will treat whateverPrecedingExpression as a function object which you want to call with your following (...)

so do sth like

whateverPrecedingExpression
;(function(Qo) {
    Qo.prototype.var2 = 2

    function secretFn(value) {
      return value
    }

    Qo.prototype.public = function(value) {
      console.log(value)
      return value
    }
    return Qo
  })(window.Qo = window.Qo || {})

Upvotes: 3

Pranay Tripathi
Pranay Tripathi

Reputation: 1842

try below code

(function(Qo = window.Qo || {}) {
    Qo.prototype.var2 = 2

    function secretFn(value) {
      return value
    }

    Qo.prototype.public = function(value) {
      console.log(value)
      return value
    }
    return Qo
  })()

have a look at this article on default parameters.

Upvotes: 1

Related Questions