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
The methods on the prototype are the methods that are available on each instance.
class Example {
constructor(private someProperty: string) {
}
method() {
return this.someProperty;
}
}
var exampleA = new Example('A');
var exampleB = new Example('B');
var exampleC = new Example('C');
console.log(exampleA.method()); // A
console.log(exampleB.method()); // B
console.log(exampleC.method()); // C
Each instance will have the someProperty
and method()
copied to its prototype. You can check this using:
alert(exampleC.hasOwnProperty('someProperty') ? 'Yes' : 'No');
It is only when the instance doesn't have its own property that JavaScript will walk up any dependency chain to find the property on a class higher up the dependency chain.
If you supply the code where you are having trouble with the scope of this
I'm sure we can help you to fix it.
It looks like this is a TypeScript/Knockout issue, as @Anzeo pointed out in his answer as well as your edit. I've gotten around the issue by putting my method declarations in the constructor but also using the var self = this;
convention pointed out in the "Managing 'this'" section on Knockout's Computed Observable documentation. You TS code could look like this:
class FooViewModel{
FooAlert: KnockoutObservableAny;
openFooAlertDialogueAdd: () => void;
constructor(){
var self = this;
self.FooAlert = ko.observable();
self.openFooAlertDialogueAdd = function(){
self.FooAlert('whatever your FooAlert observable takes');
};
}
}
No matter what scope change might occur, the JavaScript closure around self
keeps you from having to worry about this
changing. That should solve both your problems.
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);
}
}