I am just beginning my journey with Typescript and I am eager to expand my knowledge. In the Official Documentation, a section on static properties caught my attention:
Static Properties
So far, we have been focusing on the instance members of a class - those that are associated with objects created from it. However, classes in Typescript can also have static members, which are associated with the class itself rather than instances of it. By using the static keyword, we can define properties or methods that are accessible directly through the class name. This is similar to how we use 'this.' for instance accesses, but with static members, we prepend the class name instead.
The code example provided illustrates this concept:
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
let xDist = (point.x - Grid.origin.x);
let yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor (public scale: number) { }
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
After making a slight modification by changing static origin = {x: 0, y: 0};
to origin = {x: 0, y: 0};
, and
let xDist = (point.x - this.origin.x);
let yDist = (point.y - this.origin.y);
The output remains the same. So, what exactly is different here? Any insights would be greatly appreciated!