因为我使用的原型(prototype)具有调用同一原型(prototype)中其他函数的函数,所以我必须使用 this
引用该方法。
问题 this
创建:
但正因为如此,我必须保留一个上下文才能使用 this
这让我变得非常丑陋.bind(this)
墙壁。
这是我为笑而制作的简化示例。
Killmyself.prototype.fireLeMissles = function () {
return new Promise(function(resolve,reject) {
this.anotherFunction(param).then(function(result) {
someList.forEach(function(item) {
this.fireLeMissles().then(function(anotherResult){
promiseList.push(anotherResult)
})
},this);
Promise.all(promiseList).then(function(promiseItem){
childPlacesIds.forEach(function(childPlaceId) {
//Do Other Stuff
},this);
});
resolve(result);
}.bind(this).catch(function(err){
console.log("Yea, life sucks sometimes.")
}));
}.bind(this));
}
Killmyself.prototype.another = function(){
//Other stuff
}
您可以看到因为调用了同一原型(prototype)中的函数,例如
this.anotherFunction(
...和this.fireLeMissles(
...我必须对上下文进行深度保存,现在(在我更大的版本中)这使得这段代码难以使用。问题:
这是一个“习惯于 JavaScript 更难的方面”的事情吗?还是你经验丰富的开发人员看到了可以避免像这样的深度绑定(bind)的简单方法?
最佳答案
如果您使用 ES6 ,您可以受益于arrow functions ,它保留了上下文。
var counter = function () {
this.count = 0;
setInterval( () => { // arrow function
console.log(this.count++); // context is preserved
}, 1000)
}
var counter = new counter();
因此,您的代码将变为:
Killmyself.prototype.fireLeMissles = function() {
return new Promise((resolve, reject) => {
this.anotherFunction(param).then(result => {
someList.forEach(item => {
this.fireLeMissles().then(anotherResult => {
promiseList.push(anotherResult)
});
});
Promise.all(promiseList).then(promiseItem => {
childPlacesIds.forEach(childPlaceId => {
//Do Other Stuff
});
});
resolve(result);
}).catch(err => {
console.log("Yea, life sucks sometimes.")
});
});
}
对于 ES5 ,您可以使用
.bind
就像你做的那样,或者你可以分配this
到具有所需上下文的函数中的其他内容,然后在内部函数中使用该变量。Killmyself.prototype.fireLeMissles = function() {
var self = this; /// use `self` instead of `this` from now on.
return new Promise(function(resolve, reject) {
self.anotherFunction(param).then(function(result) {
someList.forEach(function(item) {
self.fireLeMissles().then(function(anotherResult) {
promiseList.push(anotherResult)
})
});
Promise.all(promiseList).then(function(promiseItem) {
childPlacesIds.forEach(function(childPlaceId) {
//Do Other Stuff
});
});
resolve(result);
}).catch(function(err) {
console.log("Yea, life sucks sometimes.")
});
});
}
关于JavaScript promise : Deep nested context with bind(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735449/