dragonfly
dragonfly

Reputation: 17773

Why functions's this keyword is set to window but window does not have function as property

(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

Answers (1)

Matt
Matt

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

Related Questions