【问题标题】:Javascript confusion for scope of 'this' inside closure function关闭函数内“this”范围的Javascript混淆
【发布时间】:2017-11-16 11:26:37
【问题描述】:

我尝试了下面的函数来理解this关键字作用域全局/私有。

我理解了 97%。但对 x.private_fa() 的输出感到困惑,该输出返回一个私有函数,但不返回其中的私有值。

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);
}

【问题讨论】:

  • 在进入函数之前将其分配给另一个变量,例如var b_internal = this.b,然后在闭包内你有b_internal,它具有正确的值。
  • 更好的是,如果您需要访问所有成员(并且可能修改它们),对 thisvar t = this 执行相同操作,然后在闭包内 return t.b;
  • 这是因为this 将引用函数调用的上下文而不是定义它的位置,您可以注意到您的对象中没有ab 属性返回f,其中调用了fa()。您可以像 Federico 所说的那样将值存储在函数(闭包)中,另一种方法是使用 ES6 的箭头函数,它有一个“稳定的”this,对应于函数的定义位置
  • 不要 return 来自使用 new 调用的构造函数的对象。

标签: javascript oop scope this


【解决方案1】:

在您发布的代码中,对x.private_fa() 的调用返回undefined,只是因为对象x 没有b 成员(而fa 返回this.b)。

如果您希望它返回该值,请让您的对象的 private_fa 返回“私有”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
};

bound_fa 函数中,this 将永远绑定到f() 上下文(所需变量b 所属的位置)。

这篇文章可以进一步阐明这个之谜:https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md

【讨论】:

  • 谢谢,这个答案看起来专业而标准。
猜你喜欢
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 2017-11-03
  • 2014-03-23
相关资源
最近更新 更多