1

Have been learning Javascript far past few months still here I end. :(

Got this below question in an interview:

var age = 10;
var obj = {
    age: 54,
    foo: () => {
      console.log(this.age);
    }
  }

const { foo } = obj;
foo();   //10

What changes would be required to make it print "54" instead of "10"?

Will appreciate a lot if someone can suggest me some source where I can study the in-depth of javascript and its engine in detail but in laymen terms.

Binay Paul
  • 11
  • 2
  • 2
    `this` changes depending on how the method is called. In your example `this` is likely the global object, and `age` is a property on that object. So `this.age` is `10` – evolutionxbox May 27 '21 at 13:09
  • 3
    This only prints `10` when in a browser, not in e.g. a Node.js script, where there is no global `this`. – AKX May 27 '21 at 13:10
  • Which part are you allowed to change? – zero298 May 27 '21 at 13:10
  • @AKX - There is, it's just normally code isn't using it. But try `node < script.js` and the code runs at global scope (and prints 10). :-) – T.J. Crowder May 27 '21 at 13:13
  • simple: `var age = 10; var obj = { age: 54, foo: () => { console.log(obj.age); } } const { foo } = obj; foo();` – Adison Masih May 27 '21 at 13:13
  • @T.J.Crowder what does the ` – evolutionxbox May 27 '21 at 13:14
  • @T.J.Crowder Ah, yeah. Fixed to the more precise "Node.js script" :-) – AKX May 27 '21 at 13:14
  • 1
    @evolutionxbox - It's command line redirection of `stdin`. Node runs code from `stdin` at global scope. Otherwise, it defaults to running files as modules (of one kind or another). – T.J. Crowder May 27 '21 at 13:15
  • @AKX - Even in them, there's a global this value, it's just not being used in that specific case. You access it via its other name, `globalThis`. (I'm not kidding you, that's in the standard now. :-D ) – T.J. Crowder May 27 '21 at 13:16

0 Answers0