如何在打字稿中的对象中使用类变量?

Kaz*_*azi 8 javascript typescript

假设我在打字稿文件中有一个类,如下所示:

export class app {
  let variable3="Hellow world"
  constructor(count){
      this.variable1="something",
      this.variable2=1+count;
   }

}
Run Code Online (Sandbox Code Playgroud)

现在在另一个文件中,我将这个类导出为:

import { app } from './directory';
let pageApp:app;
Run Code Online (Sandbox Code Playgroud)

现在,我如何在这里访问这些变量?

Tit*_*mir 12

您对类的定义在语法上不正确,let在类中没有并且在语义上不正确,您需要声明所有字段:

// appClass.ts
export class app {
    variable1: string // implicitly public in typescript
    variable2: number
    variable3 = "Hellow world"
    constructor(count : number) {
        this.variable1 = "something";
        this.variable2 = 1 + count;
    }

} 
Run Code Online (Sandbox Code Playgroud)

关于用法,导入应该没问题,但是您需要导入类所在的文件(不是导入建议的目录),并且您需要新建类以创建实例

import { app } from './appClass'; // notice no extension (no .js or .ts)
let pageApp:app = new app(1);
console.log(pageApp.variable2);
Run Code Online (Sandbox Code Playgroud)


Unl*_*yAj 5

参考 --> Typescript 类

假设您的班级为:

export class app {
   //you can specify Public, private, and protected modifiers
   // default consider as public so you can access in other class as well.

   public variable1="Hellow world";
   public variable2: any
   public variable3: any;

  constructor(count){
      this.variable1="something",
      this.variable2=1+count;
   }
}
Run Code Online (Sandbox Code Playgroud)

导入到另一个文件中

import { app } from './directory';
let var_name = new app('pass_count_here')

//Access
var_name.variable1
Run Code Online (Sandbox Code Playgroud)


jon*_*ach 5

通常,术语类变量用于属于类成员的变量,即存在于类上但不存在于实例上的变量。这意味着,它们在构造任何实例之前就存在。

在 TypeScript 中,这些类变量是使用static关键字创建的。(这就是为什么它们也被称为静态方法的原因。)在您的示例中,只能variable1创建一个类变量,因为其他两个变量是实例成员(也称为实例变量),因为它们在实例化期间获取它们的值 -在方法中 constructor

为了创建variable1一个类方法,static请像这样创建它:

export class app {
   static variable1 = "Hello, World";

   public variable2: any;
   public variable3: any;

  constructor(count){
      this.variable1 = "something";
      this.variable2 = 1 + count;
   }
}
Run Code Online (Sandbox Code Playgroud)

现在,可以从类中对其进行寻址app,而无需任何实例化:

console.log(app.variable1)  // Hello, World
Run Code Online (Sandbox Code Playgroud)