Nev*_*vin 5 javascript json var function this
嗨,我正在尝试调用一个JSON中属性值的函数.
在不同场景中获得不同的结果
var x = 3;
var foo = {
x: 2,
inner: {
x: 1,
reValue: function() {
return this.x
}
}
}
var go = foo.inner.reValue;
Run Code Online (Sandbox Code Playgroud)
情况1:
console.log(go()) // 3
Run Code Online (Sandbox Code Playgroud)
案例2:
console.log(foo.inner.reValue()) // 1
Run Code Online (Sandbox Code Playgroud)
谁能解释案例1?
在全局范围内创建一个变量,自动将其分配给window,因此:
var x = 3;\n var go = foo.inner.reValue;\n go()\nRun Code Online (Sandbox Code Playgroud)\n\n与以下操作相同:
\n\n window.x = 3;\n window.go = foo.inner.reValue;\n window.go();\nRun Code Online (Sandbox Code Playgroud)\n\n最后一行将go使用上下文(也称为this)being进行调用window,因此this.xwill be window.x。
\n\n如果在对象上调用函数(例如 in
\nobj.myMethod()或等效的 )obj["myMethod"](),则 ThisBinding 将设置为该对象(obj在示例中为 \xc2\xa713.2.1)。~ this 关键字如何工作?