【发布时间】:2018-12-24 15:32:19
【问题描述】:
鉴于以下 JS 代码,当通过 bar.fun.call(b, 'hi'); 调用 bar.fun 时,我如何告诉编译器我希望 this 成为 Banana 的实例?
/**
* @typedef {Object} Bar
* @property {function(this:Foo, string):number} fun
*/
class Foo {
constructor(){
this.n = 1;
};
}
class Banana extends Foo {
constructor() {
super();
this.b = 2;
};
}
const b = new Banana();
/** @type {Bar} */
const bar = {
/**
* @this {Banana}
* @param {string} s
* @return {number}
*/
fun(s) {
return this.n + this.b + s.length; //Property 'b' does not exist on type 'Foo'
}
};
bar.fun.call(b,'hi');
【问题讨论】:
-
首先,如果您使用的是 TypeScript,您应该在使用
this.smth访问它们之前定义类属性。例如。在Foo的构造函数上方,您应该编写类似public n: number;的内容。请编辑您的代码。否则,删除typescript标签。 -
我不是在写 TS。我正在使用 JSDoc 注释编写 JS,然后使用 Typescript 进行编译。
标签: typescript jsdoc