Amit Shah
Amit Shah

Reputation: 8179

Javascript confusion for scope of 'this' inside closure function

I tried below function to understand this keyword scope global/private.

I understood it 97%. but got stuck in confusion over the output of x.private_fa() which returns a private function but not the private value inside it.

a = 1.1;
b = 2.1;
c = 3.1;

function fa() {
  return "Global fa()";
}

function f() {
  var a = 1;
  this.b = 2;

  function fa() {
    return this.b; // or this.a not working..!
    //return b // 2.2
    //return a // 1
  }

  return {
    private_a: a, // 1
    global_a: window.a, // 1.1
    private_b: this.b, // 2
    global_b: b, // 2.1
    private_fax: fa(), // 2.1
    private_fa: fa, // function private fa()
    global_fa: window.fa(), // Global fa()
    global_c: c, // 3.1
    private_c: this.c // 3
  };
}

try {

  f.prototype.c = 3;

  var x = new f();

  f.prototype.c = 4;

  console.log("x:", x);

  /*??? Please explain this.. ??? */
  console.log("x.private_fa():", x.private_fa());

  console.log(x.private_c);
  var x1 = new f();
  console.log(x1.private_c);

  console.log(" - End - ");
} catch (e) {
  console.error("Error: ", e.message);
}

Upvotes: 1

Views: 62

Answers (1)

p-a-o-l-o
p-a-o-l-o

Reputation: 10047

In the code you posted, a call to x.private_fa() returns undefined, just because the object x hasn't a b member (and fa returns this.b).

If you want it to return that value let your object's private_fa return a bound version of the "private" fa():

var bound_fa = fa.bind(this);

return {
    private_a: a, // 1
    global_a: window.a, // 1.1
    private_b: this.b, // 2
    global_b: window.b, // 2.1
    private_fax: fa(), // 2.1
    private_fa: bound_fa, // function private fa()
    global_fa: window.fa(), // Global fa()
    global_c: window.c, // 3.1
    private_c: this.c // 3
};

In bound_fa function, this will be forever tied to f() context (where the desired variable b belongs).

This reading could clarify the this enigma further: https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md

Upvotes: 1

Related Questions