📜  Node.js 这个绑定

📅  最后修改于: 2022-05-13 01:56:20.434000             🧑  作者: Mango

Node.js 这个绑定

箭头函数不绑定自己的“this”值。相反,定义它的范围的“this”值是可访问的。这使得箭头函数不适合方法,因为这不会是对定义该方法的对象的引用。

对于方法,ES6 提供了新的方法定义语法。您可以在下面的 printGuestList 方法的定义中看到这一点。该函数是一个标准函数,只是具有允许删除冒号和函数关键字的简写语法。

因为箭头函数不绑定 this,所以它们适用于除方法之外的所有内容。如下所示,传递给 forEach 的箭头函数能够正确访问 this.name,因为它被定义为箭头函数并且没有自己的 this 绑定。如果您将箭头函数换成标准函数,该代码将不起作用。

创建一个文件夹并添加一个文件,例如index.js 。要运行此文件,您需要运行以下命令。

node index.js

文件名:index.js

// 'This' in Arrow function
const eventOne = {
    name: 'Birthday Party',
    guestList: ['Gourav', 'Vijay'],
    printGuestList() {
        console.log('Guest list for ' + this.name);
        this.guestList.forEach((guest) => {
            console.log(guest + ' is attending ' + this.name)
        });
    }
}
  
// 'This' in normal function
const eventTwo = {
    name: 'Birthday Party',
    guestList: ['Gourav', 'Vijay'],
    printGuestList() {
        console.log('Guest list for ' + this.name);
        this.guestList.forEach(function (guest) {
            console.log(guest + ' is attending ' + this.name)
        });
    }
}
  
eventOne.printGuestList();
console.log('---------------------');
eventTwo.printGuestList();

运行程序的步骤:

  • 使用以下命令运行 index.js 文件:
    node index.js

    上述命令的输出

这就是“this”绑定在箭头函数和普通函数上的工作方式。