javascript - 从方法错误 "X is not a function"调用方法

标签 javascript reactjs

我是 javascript 的新手,我正在做一个小应用程序作为练习,但我遇到了一个奇怪的问题。我试图在同一个类的另一个方法中调用一个方法,但它并不总是有效。

export class Core {
constructor() {
    this.promptList = ["Are you sure you want to proceed? [Y/n] ",
                        "Enter a username: ",
                        "Enter your email: "];
    this.funcList = [this.proceed,
                    this.validateUser,
                    this.validateEmail];

    this.currentStep = 0;
}

incStep(state) {
    const newState = Object.assign({}, state,
        {prompt: this.promptList[++this.currentStep]});
    return newState;
}

printError(state, error) {
    console.log("error");
    return Object.assign({}, state,
        {history: state.history.concat(error)});
}

proceed(input, state) {
    if (input == "Y")
        return this.incStep(state);
    else if (input == "n")
        return this.printError(state, "ok bye");
    return state;
}

validateUser(input, state) {
    return state;
}

validateEmail(input, state) {
    return state;
}

process(input, currentState) {
    const newState = Object.assign({}, currentState,
        {history: currentState.history.concat(input)});
    return this.funcList[this.currentStep](input, newState);
}

在 process() 中,我从函数列表中调用一个方法,这工作正常,但是当我尝试从 proceed() 中调用 incStep() 时,抛出错误

Uncaught TypeError: this.incStep is not a function
at Array.proceed (http://localhost:8080/index_bundle.js:31881:34)
at Core.process (http://localhost:8080/index_bundle.js:31898:42)

我猜这个错误是由于“this”没有引用好的对象,但我不明白为什么在这种情况下:/

我在这里做错了什么?

最佳答案

您的代码因这些部分而失败。

this.funcList = [this.proceed,
                this.validateUser,
                this.validateEmail];

你需要记住数组在 js 中是一种特殊的对象,所以它等价于

this.functList = {0:refrence of proceed,
                  1:refrence of validateUser,
                  2:refrence of validateEmail,
                  length:3
                  }

当函数作为对象的方法被调用时,它的 this 被设置为调用该方法的对象。 所以当

 this.funcList[this.currentStep](input, newState);

被调用并执行,这属于它所在的对象,在本例中是 funcList 数组。

proceed(input, state) {
if (input == "Y")
    return this.incStep(state);

因此在 proceed 中的这个调用引用了 funclist 数组而不是类并且失败了。

使用绑定(bind)设置 this 是解决此问题的一种方法。

this.funcList = [this.proceed.bind(this),
                 this.validateUser.bind(this),
                 this.validateEmail.bind(this)];

关于javascript - 从方法错误 "X is not a function"调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46282468/

相关文章:

javascript - 不能同时在 X Y Z 轴上旋转

image - Webpack 需要 React 组件中的动态图像

javascript - 设置为 null 后标题仍然显示

reactjs - 匿名函数如何在 React 组件的 onClick 中工作?

javascript - 使用HTML5 + javascript进行演示的基本框架

javascript - 单击 D3 饼图段时 this.set() 不是函数

javascript - 如何访问 CLI 参数的多个值

javascript - 我如何从检查元素中知道cpanel中的文件源代码?

reactjs - React 导入组件文件夹

reactjs - fireEvent.change 不会切换复选框