避免在 JavaScript 类型函数中使用 self=this
Avoid self=this in JavaScript type functions
如何避免在每个类型函数中在 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
) 因为你必须看看你的范围。更何况感觉没有必要声明额外的变量。
假设你有 ES6(我看到 const
的用法),arrow functions should be available. More information can be found in this section of the same page。
您可以使用 Function.prototype.bind 将 this 关键字设置为提供的值:
Server.prototype.listen = function() {
setTimeout(function() {
console.log(this.config);
}.bind(this));
};
或者在 ES2015 就绪环境中,您可以使用 arrow functions,它具有词法 this 值:
Server.prototype.listen = function() {
setTimeout(() => {
console.log(this.config);
});
};
如何避免在每个类型函数中在 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
) 因为你必须看看你的范围。更何况感觉没有必要声明额外的变量。
假设你有 ES6(我看到 const
的用法),arrow functions should be available. More information can be found in this section of the same page。
您可以使用 Function.prototype.bind 将 this 关键字设置为提供的值:
Server.prototype.listen = function() {
setTimeout(function() {
console.log(this.config);
}.bind(this));
};
或者在 ES2015 就绪环境中,您可以使用 arrow functions,它具有词法 this 值:
Server.prototype.listen = function() {
setTimeout(() => {
console.log(this.config);
});
};