Reputation: 2077
I'm developing some JavaScript that will sit on a SharePoint page. SharePoint provides a global function getCurrentCtx(). Unfortunately this function is only available on certain pages. My JavaScript needs to test to see if this function exists.
Easy, right?
if(getCurrentCtx) {
//Code here
}
Not so fast:
Uncaught ReferenceError: getCurrentCtx is not defined
WTF? If it's not defined, it should be undefined
which is falsey and so the if statement should simply be skipped.
console.log(getCurrentCtx)
Uncaught ReferenceError: getCurrentCtx is not defined
As far as I know, the uncaught referencerror exception occurs when you try to call a function that doesn't exist. So why am I getting it when I'm just trying to retrieve the value of a variable?
Thanks,
YM
Upvotes: 0
Views: 299
Reputation: 816482
As far as I know, the uncaught referencerror exception occurs when you try to call a function that doesn't exist.
Incorrect.
If you are trying read the value of any variable (or more general, binding) that doesn't exist (e.g. no var getCurrentCtx
anywhere), then JS throws a reference error.
Relevant part in the specification.
Exception: typeof getCurrentCtx
would return "undefined"
, because it tests whether the variable (reference) is resolvable (exists) before it reads it.
Upvotes: 3
Reputation: 60527
Variables that are not declared throw the Uncaught ReferenceError
exception. Undefined properties return undefined
. Something like this will probably work.
if(typeof getCurrentCtx !== "undefined") {
//Code here
}
Alternately, the following might also work.
if(self.getCurrentCtx) {
//Code here
}
Both of these are untested on Sharepoint, but would work in plain JavaScript.
Upvotes: 1