我尝试使用以下函数来理解this
关键字范围global / private。
我明白了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);
}
答案 0 :(得分: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