在JavaScript类型的函数中避免self-this

Avoid self=this in JavaScript type functions

本文关键字:self-this 函数 JavaScript 类型      更新时间:2023-09-26

如何避免在JavaScript/Node.js中的每个类型函数中执行const self = this

function Server(config) {
    const self = this;
    this.config = config;
    setTimeout(function() {
        console.log(self.config);
    }, 2000);
}
Server.prototype.foo = function() {
    const self = this;
    setTimeout(function() {
        console.log(self.config);
    }, 4000);
};
module.exports = Server;

它非常容易出错(我使用this还是self,因为您必须查看您的范围。更不用说声明额外的变量了。

您可以使用Function.prototype.bind将this关键字设置为提供的值:

Server.prototype.listen = function() {
  setTimeout(function() {
    console.log(this.config);
  }.bind(this));
};

或者,在ES2015就绪环境中,您可以使用具有词法this值的箭头函数:

Server.prototype.listen = function() {
  setTimeout(() => {
    console.log(this.config);
  });
};

假设您有ES6(我看到了const的用法),箭头函数应该是可用的。更多信息可以在同一页的这一部分找到。