Is it possible to force typescript to put methods on the instance not the prototype. I ask this because I frequently have \"this\" scope issues which having methods on the proto
If you're having scope issues I feel bad for you son, I've got 99 problems but this
ain't one!
Steve's answers show the correct way to define class methods, methods that will be exposed on each instance. However, if you're encountering scope issues, this is probably due to the fact you're calling those methods from another context.
For example, if you're using Knockout and you bind one of those methods to a click
binding, Knockout will override the scope to the current scope of the binding, NOT the scope you have defined the method on.
There are two options to prevent this loss of scope.
Firstly you can define your methods in the constructor, to expose them on the instance instead of on the prototype.
Like:
class Greeter {
greet:() => string;
greeting: string;
constructor(message: string) {
this.greeting = message;
this.greet = () => {
return "Hello, " + this.greeting;
}
}
Secondly, you could use the =>
syntax to scope your class methods.
Example:
class Greeter {
greeting: string;
constructor() {
this.greeting: "Blabla";
}
greet= () => {
alert(this.greeting);
}
}