我在类的成员函数中使用了async.series
,但无法访问此引用,因此无法访问async.series
函数中该类的成员-对此有什么解决方法吗?
如何在类中声明async series
模式并访问async series
模式中的类成员?
async = require("async");
class X {
constructor() {
this.member = 1; /*< --- member declaration*/
}
f(){
async.series([ /*< --- async declaration*/
function (cb) {
console.log('s1')
cb();
},
function (cb) {
console.log('s2')
console.log(this.member) /*< --- member access failing here*/
cb();
}
], function(){
console.log('here')
});
}
}
(new X()).f()
以下是输出:
s1
s2
TypeError: Cannot read property 'member' of undefined
at /home/runner/KnowledgeableFrequentStatistic/index.js:14:26
at /home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:2948:28
at replenish (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:440:21)
at /home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:445:13
at eachOfLimit$1 (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:471:34)
at awaitable (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:208:32)
at eachOfSeries (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:658:16)
at awaitable (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:208:32)
at /home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:2947:9
at awaitable (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:208:32)
这是因为您使用function(cb)
而不是(cb)=>{}
。如果您尝试控制台日志this
,您将看到this
就是函数。这与范围界定有关。https://www.w3schools.com/js/js_scope.asp会给你更多的信息。另一个有更多信息的地方:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this