为什么这在 google chrome 开发工具的范围选项卡中具有未定义的值?我期待这个:window

Why this has a value of undefined in the scope tab of google chrome dev tools? I was expecting this: window

我下面的脚本使用 reduce() 方法将数组 [[0, 1],[2, 3],[4, 5]] 转换为 [1, 2, 3, 4, 5]

调试此脚本时,我注意到在 Chrome 开发工具(见下面的屏幕截图)的范围选项卡中,this 的值为未定义。你能给我解释一下为什么吗?我期待这个:window.

P.S:我知道有 flate() 方法,但我的问题是关于 this 值。

提前致谢。

const flattened = [
  [0, 1],
  [2, 3],
  [4, 5]
].reduce(
  (acc, item) => {
    debugger;
    return acc.concat(item)
  }, []);

您使用的是箭头函数,它与普通函数相比有一些不同。箭头函数没有 this 值。

如果替换箭头函数

(acc, item) => {

功能正常,

function (acc, item) {

然后'this'将被设置为'Window'。

--

代码示例和更多信息here

let user = { 
    name: "GFG", 
    gfg1:() => { 
        console.log("hello " + this.name); // no 'this' binding here 
    }, 
    gfg2(){        
        console.log("Welcome to " + this.name); // 'this' binding works here 
    }   
 }; 
user.gfg1(); 
user.gfg2(); 

--

编辑:您的代码确实有效,只是对 const 本身的赋值没有 return 值,因此在控制台上打印 "undefined" 。要打印出 const 中的值,只需将其添加到末尾即可:

const flattened = [
  [0, 1],
  [2, 3],
  [4, 5]
].reduce(
  (acc, item) => {
    return acc.concat(item)
  }, []); 
flattened

输出:

(6) [0, 1, 2, 3, 4, 5]

由于您在箭头函数中,它将使用词法范围来确定 this 的值。

每当我在函数中看到 this 关键字时,我都会采取这些步骤来弄清楚它引用的是什么。摘自 here

  1. 查看调用函数的位置。
  2. 点左边有物体吗?如果是这样,那就是 “this”关键字正在引用。如果没有,继续#3。
  3. 函数是用“call”、“apply”还是“bind”调用的?如果是这样, 它将明确说明“this”关键字所引用的内容。如果 不是,继续#4.
  4. 是否使用“new”关键字调用函数?如果是这样,“这个” 关键字引用由 JavaScript 翻译。如果没有,继续#5。
  5. “this”是在箭头函数中吗?如果是这样,它的参考可能是 在封闭(父)范围内按词法找到。如果没有,继续 #6.
  6. 你在“严格模式”吗?如果是,则“this”关键字未定义。 如果没有,继续#7。
  7. JavaScript 很奇怪。 “this”引用“window”对象。