-1

function A() {
  return function B() {
    return this;
  };
}
A = {
  B: function B() {
    return this;
  }
};

Why thisin the B() return window object instead of the function A() object? Function in JS is an object, so why is it behaving different which is shown in the second code sample?

DNAngel
  • 7
  • 4
  • because 'this' is a keyword which holds the scope of the function and not the function – Jayabalaji J Nov 22 '17 at 07:03
  • @JayabalajiJ Function in JS is an object, so the 'this' keyword in B() should be returning the A() function object instead of window. – DNAngel Nov 22 '17 at 07:06

1 Answers1

2

Your function B is just declared in the function A, it has nothing else with function A, except the scope. Every function has it own context to which this refers. By default (means no explicit/implicit bindings, no object) this refers to the window object in non strict mode and to the undefined in strict mode.

Non strict mode

function A() {
  return this;
}

console.log(A());

Strict mode

'use strict';

function A() {
   return this;
}

console.log(A());

Explicit binding

'use strict';

const obj = { name: 'Object' };

function A() {
   return this;
}

console.log(A.call(obj));

Object binding

const obj = {
  name: 'Object',
  A() {
     return this;
  }
}

console.log(obj.A());
Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101
  • This is not the answer I am looking for. I am asking why B() this keyword inside A() return window. – DNAngel Nov 22 '17 at 07:09
  • 1
    Have you read the above part ? Your function B is just declared in the function A, it has nothing else with function A, except the scope. Every function has it own context to which this refers. By default (means no explicit/implicit bindings, no object) this refers to the window object in non strict mode and to the undefined in strict mode. – Suren Srapyan Nov 22 '17 at 07:09
  • Function in JS is an object, so 'this' keyword in B() should be returning empty A() object instead of window. – DNAngel Nov 22 '17 at 07:15