javascript - 绑定(bind)范围 javascript

标签 javascript node.js scoping

我正在尝试找出使用绑定(bind)的范围。我对 boundF1 的输出感到困惑。这是怎么回事?

// console.log(x) ReferenceError: x is not defined

// setting this.x - this here is global or window
this.x = 5;
console.log(x) // 5

function f1() {
  console.log(x); // 5
  console.log(this.x); // 5
}

// Lexically bound this to window 
f2 = () => {
  console.log(x); // 5
  console.log(this.x); // 5
}

f1()
f2()

boundF1 = f1.bind({x:1});
boundF2 = f2.bind({x:1});


boundF1() // 5 1 Why is this not 1, 1. How is x resolved here? Does it check local vars, then global vars. Would it ever use this? What is the scoping rule?

boundF2() // 5 5

最佳答案

因为x将始终在范围内查找变量。它与this(上下文)无关。当您调用 .bind 时,您只需在函数内部设置 this 的值。

关于javascript - 绑定(bind)范围 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57725077/

相关文章:

javascript - 登录成功后返回 Angular 页面吗?

node.js - 什么是 Node.js 隔离?为什么他们现在死了?

javascript - 嵌套函数可以访问它们的范围 "above"...但是它们在哪里定义有关系吗?

javascript - Typescript 中此子范围的问题

r - 从全局环境访问对象,这些对象直接传递给 ggplot 包装器中的函数

JavaScript 在 json 中搜索

javascript - Cypress :如何针对 window.fetch POST 请求正文的内容进行断言?

javascript - 当父组件和子组件都是函数组件时,如何将函数作为 Prop 传递?

javascript - async.auto 中的竞争条件

node.js - 将附加参数传递给 Mongoose 查询