Two common issues frequently discussed on SO (especially those tagged with TypeScript
) are presenting themselves to you.
The first problem arises when you perform an asynchronous operation like so:
dtJSONLoad();
console.log(settings);
Your console.log
statement is running before the completion of the dtJSONLoad
, resulting in the settings
variable being undefined.
The second console.log
reflects the true value upon the async operation's completion.
The issue also involves the scope of this
:
When assigning a function to xobj.onreadystatechange
, that function does not correspond to the current this
, causing it to point to the Window
object upon execution.
There are two ways to address this:
(1) Employ an arrow function to retain the existing scope of this
:
xobj.onreadystatechange = () => {
// ...
};
(2) Utilize the Function.prototype.bind method:
xobj.onreadystatechange = function () {
// ...
}.bind(this);
Edit
In a namespace, the concept of this
doesn't apply due to its compilation into javascript.
For instance, consider this scenario:
namespace mynamespace {
console.log(this); // Error: 'this' cannot be referenced in a module or namespace body
}
This results in:
var mynamespace;
(function (mynamespace) {
console.log(this);
})(mynamespace || (mynamespace = {}));
An equivalent method would involve:
function fn() {
console.log(this);
}
In both cases, this
points to the Window
object.
If you modify it as follows:
namespace mynamespace {
export function fn() {
console.log(this);
}
}
mynamespace.fn();
You'll observe the output as: Object {}
, which is accurate because the fn
resides within mynamespace
.
Here's how it appears in JavaScript:
var mynamespace;
(function (mynamespace) {
function fn() {
console.log(this);
}
mynamespace.fn = fn;
})(mynamespace || (mynamespace = {}));