Reputation: 386
Trying to make a static function give access to a property xdate, which was initialized in the constructor (in typescript 1.5.3).
this.xdate is accessible in all other instance methods. it remains inaccessible in the static method.
Q. Is there anyway I can make this.xdate accessible in the static method?
Below is my code:-
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
*/
Any pointers would be of great help. (If this is a repeated question, apologies in advance)
/* UglyHack#1: since static methods are available even before the instance of an object, I created a tmp obj. within staticvroom(){} and it worked.
static staticvroom(){
console.log((new vehicle).xdate);
}
Not sure the performance issues on this.
*/
Upvotes: 0
Views: 4172
Reputation: 1138
You need to pass instance as parameter
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);
Upvotes: 4