javascript - 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'上不存在。
解决方案
一方面,你必须在你的构造函数中设置你的属性,另一方面,你在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();
}
}
推荐阅读
- ajax - Django / Ajax / 数据表
- outlook-2010 - Outlook 任务中的自定义表单未同步
- javascript - 活动未登记
- java - 使用包含文件夹中的字符 # 的 JDK SAX 解析器解析 xml 文件总是失败
- c# - 如何获取 Windows 的累积更新版本?
- node.js - Angular App 指向 localhost 而不是远程服务器进行数据请求
- ansible - ansible playbook 中的混合策略
- python - 如何随机打乱 5D 矩阵的深度、高度、宽度?
- unit-testing - Symfony 4:如何在 KernelTestCase 中加载 DataFixtures
- python - Python 列表未正确获取最小值和最大值