【问题标题】:How to use @this and function.call together?如何同时使用@this 和 function.call?
【发布时间】: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


【解决方案1】:

您有两个相互冲突的定义。在Bar的定义中,你说thisFoo类型,后来你把bar注释为有Bar类型,但是给fun一个不兼容的类型。我认为,如果您不注释 bar 并推断其类型,您将获得所需的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-20
    • 2014-06-22
    • 2013-04-24
    • 2017-01-18
    • 1970-01-01
    • 2011-10-21
    • 2012-02-27
    • 1970-01-01
    相关资源
    最近更新 更多