打字稿中类和对象的区别

时间:2016-05-30 20:18:03

标签: javascript typescript ecmascript-5

有人可以解释一下打字稿中类和对象之间的区别。

<div class="btn btn-small btn-danger">kirka</div>

在我使用之前

class greeter{
  Name: string;
  Sayhello(){
    console.log("hello")
  }
}

2 个答案:

答案 0 :(得分:4)

有许多差异。在基本级别上,类是一个对象,可用于创建具有特定形状和功能的其他对象。它为功能提供了语法糖,使用普通对象和函数可以完成更多工作。

你应该花点时间阅读TypeScript Handbook中的哪些类,因为详细回答你的问题等同于写一本书的几章 - 特别是在为TypeScript定制时。

答案 1 :(得分:1)

由你决定。这两个都是有效且惯用的TypeScript:

guard let containerURL = fileManager.containerURLForSecurityApplicationGroupIdentifier(Constants.appGroupIdentifier) else {
        return nil
}

let libraryURL = containerURL.URLByAppendingPathComponent("Library", isDirectory: true)
let cachesURL = libraryURL.URLByAppendingPathComponent("Caches", isDirectory: true)
return cachesURL.URLByAppendingPathComponent("videoFile.mov")

class Greeter {

    name: string;

    sayHello() {
        console.log("hello")
    }
}

如果您不需要课程,请不要使用它们。

但如果你想要,你可能会发现课程的好处:

  • 导出类型定义
  • 使用依赖注入管理您的依赖项
  • 单元测试您的代码
  • 使用多个实例
  • 使用多态“

我怀疑你可能没有做过这些。