-1

Here is my code showing that "var B" is targeting a global variable:

function koo(){
  console.log( this.B );
 }

 var sampleObj = {
   B: 2,
   koo: koo
 };

 var xyz = sampleObj.koo;
 
 var B = "It's global";
 xyz(); 
Montu Patel
  • 115
  • 1
  • 1
  • 7
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Cypher Jul 03 '17 at 18:24
  • Related: https://stackoverflow.com/questions/25197480/why-does-x-defined-inside-a-function-become-a-global-variable-when-i-didnt-de?rq=1 – Cypher Jul 03 '17 at 18:29
  • it's not a using scoping .why all you sent these kind of links ? – Montu Patel Jul 03 '17 at 18:33
  • Guys, don't mistake scope with binding. They're two completely different things. – slebetman Jul 03 '17 at 18:38
  • Because JavaScript doesn't autobind properties. `sampleObj.koo` returns the exact same value you assigned to it: `xyz === koo`. If you want it to behave different you need to bind the function yourself: `var xyz = sampleObj.koo.bind(sampleObj);` or simply `var xyz = koo.bind(sampleObj);`. – Felix Kling Jul 03 '17 at 18:38
  • `this` will be the space to the left of the right-most dot upon calling. if nothing else, global. – dandavis Jul 03 '17 at 19:11

1 Answers1

0

you are not executing it like sampleObj.koo(), and taking a direct reference to xyz so it is impossible to know from where it taken from, it cab be associated with so many object (or even not to anyone) with the same reference. if you want to invoke some function (reference you have) from outside in the monitor of a object, try calling xyz.call(sampleObj) instead

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
  • ok. then what about i use function that invoke (koo) ? – Montu Patel Jul 03 '17 at 18:31
  • so where is `koo` actually as "koo"? inside `sampleObj` right? then call it like `sampleObj.koo()`, if you take a reference of `koo` and want to execute directly it will never remember the scope. I hope it will help :) – Koushik Chatterjee Jul 04 '17 at 07:26