为什么我的函数secondMethod不是函数TypeError:(…).secondMethod不是函数

问题描述 投票:0回答:2

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

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是为什么它被认为是“不是一个函数”,要有人看我在这方面有什么错吗?

javascript function methods chain
2个回答
0
投票

this是您需要的


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.