首页 > 解决方案 > TS 对象上无法访问的方法

问题描述

我正在尝试使用 Vue 组件中存储在 Typescript 类中的方法。

当尝试从另一个类(恰好是 Typescript Vue 组件)使用在所述类上定义的方法时,向控制台返回 Uncaught TypeError 说我尝试使用的方法不是函数

考虑以下 Paper 类:

export class Paper {
    paperSize: number;
    documentTitle: string;

    constructor() {
        paperSize = 1;
        documentTitle = "Arbitrary title";
    }

    getDocumentRatio(): number {
        return ArbitraryLibrary.arbitraryNumericFunction(this.paperSize);
    }
}

当尝试在另一个类中使用此类(Vue 组件)时,例如:

@Component()
export class PaperUser {
    paper = new Paper();
    paperUserMethod() {
        ...
        const unimportant = this.paper.getDocumentRatio();
        ...
    }
    ...
    // Wherever the method gets used
        this.paperUserMethod();
    ...
}

然后中断该方法的执行,因为以这种方式使用该函数会创建 TypeError

最初认为这可能是一个有约束力的问题,我尝试了更像

...
this.paper.getDocumentRatio().bind(this.paper);
...

但显然这不起作用,因为以这种方式绑定将与方法链接一样有效 - IDE(VSCode)断言属性'bind'在类型'number'上不存在。

标签: javascripttypescriptvue.js

解决方案


一方面,你必须在你的构造函数中设置你的属性,另一方面,你在this.myAttribut你的类的方法实现中使用你的方法,你可以试试这个:

class Paper {
    paperSize: number;
    documentTitle: string;
    constructor() {
        this.paperSize = 1;
        this.documentTitle = "Arbitrary title";
    }
    getDocumentRatio(): number {
        // try to be trivial on first attempt
        return this.paperSize;
    }
}

class PaperUser {
    paper = new Paper();
    paperUserMethod() {
        return this.paper.getDocumentRatio();
    }
    usePaperuser(){
        this.paperUserMethod();
    }
}

推荐阅读