0

i am trying to understand different aspects of closure.Here i have created a nested closure of function returning functions.I called the first function which this is bound to another object called "obj".First outpup is set to current object "obj".But the inner function's "THIS" is set to original "WINDOW" object.Why the are not pointing to "obj" variable.Because first "THIS" is set to "obj".Other "THIS" should be set to "obj" too,shouldn't it ?

function one(){
   console.log(this);
   return function(){
      console.log(this);
      return function(){
         console.log(this);
      }
   }
}
var obj={};
one.call(obj)()();

output is :

obj

window

window

AL-zami
  • 7,637
  • 11
  • 53
  • 104
  • 1
    `this` depends on how the function is invoked and not where it is defined. – Tushar Apr 15 '16 at 08:36
  • Your first invocation uses obj as context and the other invocations on the returned functions do not use any context binding so you end up Object {}, window, window. If you run like one.call(obj).call(obj).call(obj); you will get Object {} Object {} Object {}. Alternatively you can make your `one` function like, `function one(){ console.log(this); return function(){ console.log(this); return function(){ console.log(this); }.bind(obj) }.bind(obj) }` – Redu Apr 15 '16 at 09:05

0 Answers0