【问题标题】:Object.create instead of object literalObject.create 而不是对象字面量
【发布时间】:2017-10-22 21:21:05
【问题描述】:

我正在努力理解这个 Object.create thingybob。我现在找不到它的用途。我的 JS 编码还很早,但我很难掌握它的概念。对我来说,这似乎使代码过于复杂。有人可以像我五岁一样向我解释吗?

我在这里阅读了这些文章: JavaScript inheritance: Object.create vs new

What is the 'new' keyword in JavaScript?

Understanding the difference between Object.create() and new SomeFunction()

Using "Object.create" instead of "new"

但它不适合我。如果我有这段代码,它将是什么样的 Object.create 以及如何调用它?

function Player (name, stopAtValue) {
  this.name = name
  this.stopAtValue = stopAtValue
}

let player = new Player('John', 16)

【问题讨论】:

  • 如果您对所提供的链接感到苦恼,我建议不要担心 Object.Create。也被视为您使用关键字let,这也可能值得您跳过经典的 JS 函数式构造函数,转而使用新的 class 装饰器,因为它会使 OOP 更易于使用。
  • 好吧,您在示例中展示的用例不会从 Object.create 中受益……您甚至没有在此处使用原型继承。
  • "如果我有这段代码,它会是什么样的 Object.create 以及如何调用它?" - last question you linked 几乎完全一样例如,只是在实例上使用了一个额外的方法。

标签: javascript object object-literal


【解决方案1】:

Object.create() 严格来说并不是 JavaScript 的必要部分。添加它是为了减轻记住使用new 的需要,并为我们所有人提供一种更明确的方式来创建从其他对象继承的实例。

让我们来看看你的代码:

function Player (name, stopAtValue) {
  this.name = name
  this.stopAtValue = stopAtValue
}

// You have to remember to use "new" here, otherwise this binding won't work:
let player1 = new Player('John', 16);
console.log(player1.name, player1.stopAtValue);

// this binding fails when "new" is omitted
let player2 = Player('John', 16);
console.log(player2.name, player2.stopAtValue);

JavaScript 开发人员只是应该从 Pascal 命名约定中知道该函数是构造函数并且应该使用 new

但是,从根本上说,您的代码和Object.create() 都可以让您获得相同的结果。只是Object.create() 消除了对new 的需求,并为您提供了一种非常明确的方式来表明您在做什么。

【讨论】:

  • 我宁愿从语言中删除 new 而不是 Object.create。这是一个更重要的原语。您可以从中轻松地派生一个 new 函数,但反过来就不是那么容易了。
猜你喜欢
  • 2012-11-03
  • 2015-08-11
  • 1970-01-01
  • 2020-03-20
  • 2011-10-02
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2012-03-27
相关资源
最近更新 更多