Reputation: 850
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
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
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