(function() {
var testFnk = function() {
console.log(this);
}
console.log(window.testFnk);
testFnk();
})();
The output of this code is:
- undefined
- Window
Can you explain why inside the function this refers to Window, but checking window.testFnk is undefined?
EDIT: As i’m looking at the answers, my question was not stated clearly. What I ment: why in both cases the logged values is either ‘undefined’ nor ‘window’?
Because in non-strict mode,
thisdefaults towindowin browser-land. In strict mode, it’ll beundefined.window.testFnkis undefined because you haven’t added thetestFnkmethod to thewindowobject. You can either do this explictly by assigning towindow, or implictly through an implicit global (which’ll throw an exception in strict mode, FYI);