Typescript:静态方法无法访问构造函数中的私有属性

时间:2017-06-23 09:25:20

标签: typescript constructor this static-methods

尝试创建一个静态函数可以访问属性xdate,该属性在构造函数中初始化(在typescript 1.5.3中)。

this.xdate可在所有其他实例方法中访问。 它在静态方法中仍然无法访问。

Q值。无论如何我可以在静态方法中访问this.xdate吗?

以下是我的代码: -

class vehicle{
  constructor(private xdate = new Date()){}

  vroom(){    console.log(this.xdate);  }
  static staticvroom(){ console.log(this.xdate);} //Warning: Property 'xdate' does not exist on type 'typeof vehicle'.


}//vehicle ends

let v1 = new vehicle;
v1.vroom(); //works

vehicle.staticvroom(); //undefined

/* this is how i executed it:- 
D:\js\Ang2\proj2\myforms\tsc_cRAP>tsc 7_.ts
7_.ts(18,42): error TS2339: Property 'xdate' does not exist on type 'typeof vehicle'.

D:\js\Ang2\proj2\myforms\tsc_cRAP>node 7_.js
2017-06-23T09:17:41.365Z
undefined

*/

任何指针都会有很大的帮助。 (如果这是一个重复的问题,请提前道歉)

/ * UglyHack#1:因为静态方法甚至在对象实例之前都可用,所以我创建了一个tmp obj。在staticvroom(){}中,它起作用了。

static staticvroom(){ 
  console.log((new vehicle).xdate); 
} 

不确定性能问题。

* /

1 个答案:

答案 0 :(得分:3)

您需要将实例作为参数传递

class Vehicle {
  constructor(private xdate = new Date()) {}
  vroom(){
    console.log(this.xdate);
  }
  static staticVar: Date = new Date();
  static staticvroom(vehicle: Vehicle) {
    console.log(vehicle.xdate);
    console.log(this.staticVar); // You can even access static vars with this
  }


}// vehicle ends

let v1 = new Vehicle;
v1.vroom(); // works

Vehicle.staticvroom(v1);
相关问题