类中嵌套函数之间的对象上下文(“this”)
希望你们都做得很好。
我有一个关于对象的上下文如何在 Node.JS(或一般的 JS)函数上工作的问题。我理解“当您在 Javascript 中调用顶级函数时,函数内的 this 关键字指的是默认对象”。例如,我有以下功能:
function nestedFunctions() {
var a = "I am a variable"
console.log("Initial context:")
console.log(this)
function one() {
console.log("First nested function, this is my this context:")
console.log(this)
console.log("First nested function, this is my a value:")
console.log(a)
function two() {
console.log("Second nested function, this is my this context:")
console.log(this)
console.log("Second nested function, this is my a value:")
console.log(a)
}
two()
}
one()
}
nestedFunctions()
给出以下输出:
Initial context:
Object Global
First nested function, this is my this context:
Object Global
First nested function, this is my a value:
I am a variable
Second nested function, this is my this context:
Object Global
Second nested function, this is my a value:
I am a variable
到目前为止,一切正常,函数获得了全局上下文。当我尝试蒙山时:
var rex = {
nestedFunctions() {
var a = "I am a variable"
console.log("Initial context:")
console.log(this)
function one() {
console.log("First nested function, this is my this context:")
console.log(this)
console.log("First nested function, this is my a value:")
console.log(a)
function two() {
console.log("Second nested function, this is my this context:")
console.log(this)
console.log("Second nested function, this is my a value:")
console.log(a)
}
two()
}
one()
}
}
rex.nestedFunctions()
输出是:
Initial context:
{ nestedFunctions: [Function: nestedFunctions] }
First nested function, this is my this context:
Object Global
First nested function, this is my a value:
I am a variable
Second nested function, this is my this context:
Object Global
Second nested function, this is my a value:
I am a variable
到目前为止一切都很好。父函数得到“this” = {nestedFunctions: [Function:nestedFunctions]} 因为是对象上下文,嵌套函数得到全局上下文因为它们没有绑定到父上下文。
但我的疑问是在下一个案例中:
class Dog {
constructor(name) {
this.name = name
}
bark() {
console.log(`Woof, my name is ${this.name}`);
}
nestedFunctions() {
var a = "I am a variable"
console.log("Initial context:")
console.log(this)
function one() {
console.log("First nested function, this is my this context:")
console.log(this)
console.log("First nested function, this is my a value:")
console.log(a)
function two() {
console.log("Second nested function, this is my this context:")
console.log(this)
console.log("Second nested function, this is my a value:")
console.log(a)
}
two()
}
one()
}
}
let rex = new Dog('Rex')
rex.nestedFunctions()
输出在哪里:
Initial context:
Dog { name: 'Rex' }
First nested function, this is my this context:
undefined
First nested function, this is my a value:
I am a variable
Second nested function, this is my this context:
undefined
Second nested function, this is my a value:
I am a variable
为什么嵌套函数上的“this”上下文在这种情况下是“undefined”而不是全局上下文,就像前面的例子一样?为什么在处理类时默认上下文是未定义的(而不是“全局”)?