在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
),因为您必须查看您的范围。更不用说声明额外的变量了。
您可以使用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
的用法),箭头函数应该是可用的。更多信息可以在同一页的这一部分找到。
相关文章:
- 在另一个函数中使用变量this
- JavaScript 中的嵌套函数和 “this” 关键字
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- 在JavaScript类型的函数中避免self-this
- IE 在 JavaScript 中抛出了一个关于 “self = this” 的异常
- “var self = this”方法背后的原理是什么?
- JSDoc:我如何记录`var self-this;`
- “var self=this”被认为是一种代码气味
- Javascript scope and self=this, _this=this, that=this
- 如何设置 var self = this;从函数外部
- 如何使用“self = this”访问类属性
- 带参数的“this”函数
- 在使用ES6类和生成器函数时,如何避免使用“self=this”破解
- 我可以用javascript提供我/the/self=this的原型定义吗
- 我可以在angularjs的$scope函数中写一个this函数吗?
- 'self = this'应用还是绑定?(骨干)
- Javascript作用域基础:.bind或self =this
- AngularJS -更新'self'通过函数以编程方式赋值
- 使用&;self = this&;bind(this)用于内部函数