【问题标题】:TS object declaration [duplicate]TS 对象声明 [重复]
【发布时间】: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


【解决方案1】:

试试这个方法:

class Singleton {

    static instance = null; // socket.io instance

    static getInstance(server) {
        if (!Singleton.instance) {
            Singleton.instance = server; // takes 'Hello' as the value
        }

        return Singleton.instance;
    }

}

let a = Singleton.getInstance('Hello');
let b = Singleton.getInstance('World');

【讨论】:

  • 谢谢,但我想要一个对象,而不是一个类。
  • 不,不要将class 仅用于静态方法。
  • @Bergi 我的猜测是这只是代码的一个示例,阿里稍后会添加它的实现。否则,它可以只是一个简单的函数,将实例封装在 const 中。我认为在对象中保留单例是没有用的。
  • @okarp 是的,它应该只是一个简单的函数,而且我同意单例通常是无用的 :-) (更糟糕的是,如果 getInstance 将实例作为参数,它甚至不是单例模式)
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2018-06-17
  • 2013-07-28
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多