When using strict
mode, the value of this
in a normal function call is undefined
. That is exactly what your situation is. Your function:
(function (global) {
"use strict";
var self = this;
...
})(window);
Is just a normal function call so this
will be undefined. If not using strict
mode, then this
in a normal function call will be set to the global object. Otherwise, this
gets set to a unique value only when the function is called some other way (with new
, with .apply()
or .call()
or as in obj.method()
).
The self
work-around you are using is for situations where this
already points at the desired object and you want to save that reference for later use in callbacks. Since that is not the case in your code and it is not clear what you are expecting to use this
for in your code, then it is not clear to use what to recommend to fix your problem without further description of what object you are trying to reference.
If you just want to reference the global object, then you can just reference global.test
in your code.
(function (global) {
"use strict";
function onDeviceReady () {
global.test = "123";
loadMapsApi();
}
function loadMapsApi () {
console.log(global.test);
}
})(window);
If you are expecting this
to point to some other object, then you will have to explain what you're expecting it to point to and then we can offer you an idea how to reference that specific object.
DO NOT just remove "use strict";
to make things work. The fact that your code doesn't work properly when using strict
mode means that your code is using a bad practice that strict
mode is designed to protect against. Instead, you should continue to use strict
mode and, instead, fix your code to stop using the bad practice and work properly with strict
mode.
For future reference, if you want to learn how Javascript decides what to set this
to inside a function call, you can read this answer: When you pass 'this' as an argument. That answer lists the five different ways that the value of this
is determined.