我正在做一个类库和一些函数,比如jQuery.each()。
如何在回调函数中定义[this]?
演示代码:
Atom
输出:
/**
* @this {Car}
* @type {function(Car):boolean}
*/
var callback_tips = function () { }
var Cars = [];
class Car {
constructor(name) { this.name = name; this.x = 0; }
Forward(step) { this.x += step; }
/** @param {callback_tips} callback */
static Each(callback) {
for (let car of Cars) { callback.apply(car, car); }
}
}
(function main() {
Cars = [new Car('A'), new Car('B'), new Car('C')];
console.log(Cars);
Car.Each(function (car) { this.name += this.name; this.Forward(5); });
console.log(Cars);
})();
VsCode截图:
Callback tips is working (Screenshot)
然后
But this do not work (Screenshot)