【问题标题】:Why my function secondMethod is not a function TypeError: (...).secondMethod is not a function为什么我的函数 secondMethod 不是函数 TypeError: (...).secondMethod 不是函数
【发布时间】:2020-05-30 16:22:19
【问题描述】:

我正在尝试为个人项目创建一个可链接的实例,我尝试了这个简单的示例并进行了一些修改,但出现了错误:

TypeError: chainableInstance.firstMethod(...).secondMethod is not a function
    at Object.<anonymous> (/Users/rodger/Developer/Projects/Personal/unknown/src/teste.js:48:33)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

我的代码是这样的:

  otherMethod(a) {
    return (this.a = a.replace('!e', 'e'));
  }
}
class Another extends Other {
  constructor() {
    super();
  }

  anotherMethod(a) {
    console.log('This is anohter method');
    return (this.a = a.replace('!d', 'd !e'));
  }

  otherMethod() {
    return super.otherMethod(this.a);
  }
}

class ChainAble extends Another {
  constructor() {
    super();
  }

  firstMethod() {
    return (this.a = 'a !b');
  }

  secondMethod() {
    return this.a.replace('!b', 'b !c');
  }

  thirdMethod() {
    return this.a.replace('!c', 'c !d');
  }
  anotherMethod() {
    return super.anotherMethod(this.a);
  }
}

const chainableInstance = new ChainAble();
chainableInstance.firstMethod().secondMethod().thirdMethod().anotherMethod();

console.log(chainableInstance);

我只是不明白为什么我的 secondMethod 被认为是“不是一个函数”,有人看看我在这件事上有什么问题吗?

【问题讨论】:

  • 调用某个类 Chainable 不会使其可链接。您实际上需要从第一个方法返回一个实例!您的任何方法都没有返回对象。
  • 这能回答你的问题吗? Method Chaining in a Javascript Class

标签: javascript function methods chain


【解决方案1】:

this 是你所需要的

示例

class Another {
  constructor() {
  }

  anotherMethod(a) {
    console.log('This is anohter method');
    this.a = a.replace('!d', 'd !e');
    return this;
  }

  otherMethod() {
    return super.otherMethod(this.a);
  }
}

class ChainAble extends Another {
  constructor() {
    super();
  }

  firstMethod() {
    this.a = 'a !b';
    return this;
  }

  secondMethod() {
    this.a = this.a.replace('!b', 'b !c');
    return this;
  }

  thirdMethod() {
    this.a = this.a.replace('!c', 'c !d');
    return this;
  }
  anotherMethod() {
    return super.anotherMethod(this.a);
  }
}

const chainableInstance = new ChainAble();
chainableInstance.firstMethod().secondMethod().thirdMethod().anotherMethod();

console.log(chainableInstance);

【讨论】:

    【解决方案2】:

    这是因为firstMethod 返回字符串'a !b'(赋值的结果)。您需要从任何需要可链接的方法中直接返回this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2019-10-05
      • 2020-02-04
      • 2019-12-18
      • 2020-06-29
      • 2020-06-17
      相关资源
      最近更新 更多