Reputation: 17773
(function() {
var testFnk = function() {
console.log(this);
}
console.log(window.testFnk);
testFnk();
})();
The output of this code is:
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'?
Upvotes: 0
Views: 54
Reputation: 75317
Because in non-strict mode, this
defaults to window
in browser-land. In strict mode, it'll be undefined
.
window.testFnk
is undefined because you haven't added the testFnk
method to the window
object. You can either do this explictly by assigning to window
, or implictly through an implicit global (which'll throw an exception in strict mode, FYI);
(function() {
window.testFnk = function() {
console.log(this);
}
console.log(window.testFnk);
testFnk();
})();
Upvotes: 1