【发布时间】:2021-08-29 12:30:36
【问题描述】:
我是 typescript 和 javascript 的新手,我想将 JS 中的代码转换为 TS 版本。当我尝试在打字稿版本中访问this 对象时,它会显示'this possibly be 'unknown' 或类似的东西。
能否请您帮助我了解您如何在TS 中实现此代码?
const singleton = {
instance: null, // socket.io instance
getInstance: (server) => {
if (!this.instance) {
this.instance = server; // takes 'Hello' as the value
}
return this.instance;
},
}
let a = singleton.getInstance('Hello');
let b = singleton.getInstance('World');
console.log(a === b); // true
console.log(a); // Hello
console.log(b); // Hello
【问题讨论】:
-
尝试将函数从箭头符号改写为普通符号。
-
谢谢,它的作品,但为什么呢?箭头函数本身就是一个对象?
-
之所以有效,是因为箭头函数作为对象属性没有 this 的引用,默认情况下它们没有绑定。如果你使用
let a = singleton.getInstance.call(singleton, 'Hello');,你仍然可以让它工作。更多关于它的信息你可以从here中学习 -
一切都是关于
function context:) -
很好,您正在将其转换为 Typescript - 您刚刚让编译器在您的 Javascript 实现中发现了一个错误!
标签: javascript typescript singleton