Reputation: 600
I have an existing angular 1.4 application I want to port to typescript. Suppose I have the following typescript class:
class my {
constructor(public msg: string) {
}
a() {
alert(this.msg);
}
}
I want both the calls below to do the same thing:
var a = new my('hello');
a.a();
var fn = a.a;
fn();
However, fn doesn't work, it's losing its scope. I know I can use fat arrow syntax ( a = () => {}
) to save the scope for a single method.
I'd want a more elegant solution, to save the this scope inside a variable and always have access to it, without having to declare each of my methods with fat arrow.
UPDATE: Sorry for the ambiguity, what I am looking for is a typescript class that will output the following Javascipt (notice the _self variable and its usage):
var my = (function () {
var self = this;
function my(msg) {
self.msg = msg;
}
my.prototype.a = function () {
alert(self.msg);
};
return my;
}());
Upvotes: 2
Views: 2217
Reputation: 7641
You can use bind:
var instance = new my('hello');
instance.a(); // Call instance method
var fn = instance.a.bind(instance); // Get bound method
fn(); // Call bound method
What do you think about using the method to obtain bound method from class:
function getBoundMethod(instance, methodName) {
return instance[methodName].bind(instance);
}
var instance = new my('hello');
instance.a(); // Call instance method
var fn = getBoundMethod(instance, "a"); // Get bound method
fn(); // Call bound method
Upvotes: 2