我正在尝试创建一个包装REST api的typescript类,并希望将各种方法组织到子对象中,以便更好地表达代码。有没有办法做到这一点,并且仍然通过方法中的'this‘保持对类实例的访问?
例如,考虑以下类:
class ApiService {
constructor() {....}
getMedia() {}
uploadMedia() {}
sendMassage() {}
recieveMessage() {}
}
我想组织上面的方法,这样我就可以像这样调用它们:
const service = new ApiService();
//to call getMedia()
service.media.get();
//to call sendMessage()
service.messages.send();
// and so on
发布于 2019-06-02 02:39:29
我认为,要实现您所要求的内容,您应该使用arrow functions,这样apiService.media
和apiService.message
对象就不会有自己的this
上下文来妨碍它们。例如:
class ApiService {
constructor(public name: string) { }
private getMedia() {
console.log(this.name+" getMedia");
}
private uploadMedia() {
console.log(this.name+" uploadMedia");
}
private sendMassage() {
console.log(this.name+" sendMessage");
}
private recieveMessage() {
console.log(this.name+" receiveMessage");
}
// instance methods
public media = {
get: () => this.getMedia(),
upload: () => this.uploadMedia()
}
// instance methods
public message = {
send: () => this.sendMassage(),
receive: () => this.recieveMessage()
}
}
请注意,这意味着ApiService
的每个实例都将拥有自己的函数值属性、message.send
等副本。它们不会像普通方法那样驻留在ApiService.prototype
上。这并不重要,除非您正在派生许多ApiService
实例。
让我们确保它能正常工作并被正确绑定:
const api1 = new ApiService("One");
const api2 = new ApiService("Two");
api1.message.receive(); // One recieveMessage
api2.message.receive(); // Two receiveMessage
api1.media.get(); // One getMedia
api2.media.get(); // Two getMedia
看起来不错。希望这能有所帮助;祝你好运!
https://stackoverflow.com/questions/56407774
复制相似问题