ES6中的箭头功能中"this"指的是什么?

tem*_*ame 48 javascript this ecmascript-6 arrow-functions

我在几个地方读过,关键的区别是" this在箭头函数中是词法绑定的".这一切都很好,但我实际上并不知道这意味着什么.

我知道这意味着它在定义函数体的大括号范围内是独一无二的,但我实际上无法告诉你以下代码的输出,因为我不知道所指的this是什么,除非它指的是胖箭头函数本身....这似乎没用.

var testFunction = () => { console.log(this) };
testFunction();
Run Code Online (Sandbox Code Playgroud)

dav*_*ave 38

箭头函数捕获this封闭上下文的值

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();
Run Code Online (Sandbox Code Playgroud)

因此,要直接回答您的问题,this您的箭头函数内部将具有与分配箭头函数之前相同的值.

  • @torazaburo迟来的回应 - 答案是它取决于原始问题中的代码片段放置的位置.如果它在顶层,如果我们在浏览器中,`this`是`window`对象,如果我们在Node环境中则是`module.exports`.关键是,箭头函数*对`this`的值没有影响*. (3认同)
  • 来自@dave的注释,你的箭头函数中的'this`将具有与分配箭头函数之前相同的值'是最终为我点击的内容. (3认同)

小智 16

为了提供大局,我将解释动态和词汇绑定.

动态名称绑定

this指的是调用该方法的对象.这是SO上经常被读的句子.但它仍然只是一个短语,非常抽象.这句话有相应的代码模式吗?

就在这里:

const o = {
  m() { console.log(this) }
}

// the important patterns: applying methods

o.m(); // logs o
o["m"](); // logs o
Run Code Online (Sandbox Code Playgroud)

m是一种方法,因为它依赖于this.o.m()o["m"]() 手段m适用于o.这些模式是我们着名短语的Javascript翻译.

还有另一个重要的代码模式,你应该注意:

"use strict";

const o = {
  m() { console.log(this) }
}

// m is passed to f as a callback
function f(m) { m() }

// another important pattern: passing methods

f(o.m); // logs undefined
f(o["m"]); // logs undefined
Run Code Online (Sandbox Code Playgroud)

它与之前的模式非常相似,只缺少括号.但结果是相当可观的:当您传递m给函数时f,您将退出m其对象/上下文o.它现在被连根拔起并且this没有任何东西(假设严格模式).

词法(或静态)名称绑定

箭头函数没有自己的this/ super/ arguments绑定.他们从父级词法范围继承它们:

const toString = Object.prototype.toString;

const o = {
  foo: () => console.log("window", toString.call(this)),
      
  bar() {
    const baz = () => console.log("o", toString.call(this));
    baz();
  }
}

o.foo() // logs window [object Window]
o.bar() // logs o [object Object]
Run Code Online (Sandbox Code Playgroud)

除了全局范围(Window在浏览器中),只有函数能够在Javascript(以及{}ES2015中的块)中形成范围.当o.foo调用箭头函数时,没有baz可以继承它的周围函数this.因此,它捕获this绑定到Window对象的全局范围的绑定.

baz被调用时o.bar,箭头函数被o.bar(o.bar包括其父词法范围)包围并且可以继承o.barthis绑定.o.bar被召唤o,因此它this必然会受到影响o.


Xin*_*Xin 7

希望这个代码展示能给你更清晰的想法。基本上,箭头函数中的“this”是“this”的当前上下文版本。看代码:

// 'this' in normal function & arrow function
var this1 = {
    number: 123,
    logFunction: function () { console.log(this); },
    logArrow: () => console.log(this)
};
this1.logFunction(); // Object { number: 123}
this1.logArrow(); // Window 
Run Code Online (Sandbox Code Playgroud)

  • 非常简短和很好的例子。使用 `function` 时,`this` 值是在调用/调用函数时创建的。因此,当您将其称为“this1.logFunction()”时,您将其称为对象“this1”的方法,而“this”指的是 this1 文字对象。另一方面,如果您使用箭头函数,则不会根据调用/调用方式创建 `this` 值,而是从词法范围继承它,在本例中为 `window` 对象,其中定义了 this1 对象。 (2认同)