gpt4 book ai didi

node.js - this 在 Node 环境中的行为

转载 作者:搜寻专家 更新时间:2023-11-01 00:43:27 25 4
gpt4 key购买 nike

function a() {
return this;
}

function b() {
return this;
}

console.log(a() === b()) //true on browser and node

但是……

function a() {
return "inside a";
}

function b() {
console.log(this.a()); //logs undefined on node, 'inside a' on browser
}

这是针对浏览器和 Node 运行的非严格模式。

最佳答案

this 的值由函数的调用方式决定。它与函数的定义方式无关。

如果你调用一个函数就像一个简单的函数一样

a()

然后,函数 a 中的 this 的值将是全局对象或 undefined 如果在严格模式下运行。

以下是控制 this 的方法:

普通函数调用

a()

this 将是全局对象或 undefined 如果在严格模式下运行。

方法调用

obj.a()

this 将设置为对象,在本例中为 obj

.apply() 或.call()

obj.a.call(obj, arg1, arg2)
obj.a.apply(obj, array)

this 将设置为作为第一个参数传递给 .call().apply()

的对象

.bind()

var m = obj.a.bind(obj)
m();

this 将设置为作为第一个参数传递给 .bind()

的对象

关于node.js - this 在 Node 环境中的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26854713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com