1

Easy question no doubt, but I'm confused why variable 'a' is undefined when called from bar(). I would expect it to be 'global a' as bar is called from the global context

var a = 'global a' 
function foo1() {
  console.log(this.a);
}
var obj1 = {
  a: 3,
  foo1: foo1
}
var bar = obj1.foo1;
bar(); // why does this result in 'undefined rather than 'global a'?

Can anyone point out what I'm missing please?

NickW
  • 629
  • 1
  • 5
  • 23
  • 2
    `this` is defined *at call time*. Calling a function as `bar()`, without context (e.g. `obj.bar()`), means its `this` is the global object. To keep the context, bind it: `var bar = obj1.foo1.bind(obj1)`. – deceze Nov 30 '18 at 14:08
  • thanks, but i'm asking why declaring 'a' makes a difference in this context? it should call 'a' - the property of the global context shouldn't it? – NickW Nov 30 '18 at 14:10
  • Please provide a self-contained example that proves that. Currently it's not really clear what you mean, since you provide two samples in one. You can provide a snippet that's executable right here on the page with the `<>` icon thingy in the toolbar. – deceze Nov 30 '18 at 14:14
  • fair enough, two seconds – NickW Nov 30 '18 at 14:14
  • sorry, that should be a bit better? – NickW Nov 30 '18 at 14:15
  • 1
    @NickW Your example logs "global a" to the console, but it would log `undefined` if all of this code were inside a function. – JLRishe Nov 30 '18 at 14:17
  • Well… it does not. You're probably executing the code in some specific environment (nested scope) where `var` vs. no `var` makes a difference. – deceze Nov 30 '18 at 14:17
  • ah ok, i was running it node, but you're right, in the browser it doesn't make a difference. thanks – NickW Nov 30 '18 at 14:20

0 Answers0