Skip to content

Instantly share code, notes, and snippets.

@jorotenev
Created October 29, 2017 21:19
Show Gist options
  • Save jorotenev/d4c879c674d5bddac1df0c8252ddeb93 to your computer and use it in GitHub Desktop.
Save jorotenev/d4c879c674d5bddac1df0c8252ddeb93 to your computer and use it in GitHub Desktop.
Comparing the different ways of defining a method in TypeScript and their effect on `this`
class SomeClass {
public a;
public b;
constructor() {
this.a = '1';
this.b = []
}
one = () => {
console.log(`one = () => {} ${this.a}`)
this.b.push('one')
}
two() {
console.log(`two() {} ${this.a}`)
this.b.push('two')
}
three = function () {
console.log(`three = funciton() {} ${this.a}`)
this.b.push('three')
}
}
let someClassObj = new SomeClass();
someClassObj.one()
someClassObj.two()
someClassObj.three()
console.log(someClassObj.b)
// Outputs
// one = () => {} 1
// public two() {} 1
// three = funciton() {} 1
// ["one", "two", "three"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment