Reputation: 644
I'm fairly new to typescript. In javascript, I would sometimes expose functions in a module through a single object (e.g. "services"). I'm trying to do the same thing in typescript but am having trouble. Here is my simplified code:
class Tester {
public publicField = "public field";
private privateField = "private field";
public services() {
return {
service1: this.getThePrivateField
};
}
public getThePublicField() {
return this.publicField;
}
private getThePrivateField() {
console.log("reached getThePrivateField");
return this.privateField;
}
}
const t = new Tester();
console.log(t.services().service1()); // returns undefined but WHY?
When I call t.services().service1(), I know the code gets inside the getThePrivateField function as I've put a console.log there. So why is the response undefined?
Upvotes: 0
Views: 208
Reputation: 998
The problem is plain old javascript this
confusion. To make what you're trying to achieve work you would need to call t.services().service1.bind(t)()
.
This arises from the fact that, in the function t.services().service1
, this
is actually the object you're returning from services()
, which doesn't have any privateField
key.
Upvotes: 1