2

I'm trying to get my head around this Object.create thingybob. I can't find a use for it right now. I'm quite early in my JS coding but I'm struggling to grasp the concept of it. To me it just seems to over complicate the code a whole lot. Could someone explain it to me like I'm a five-year-old?

I have read these articles here: 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"

But it doesn't do it for me. If I have this code what would it look like as an Object.create and how could it be called upon?

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

let player = new Player('John', 16)
Thomas Bengtsson
  • 399
  • 2
  • 10
  • 22
  • If your struggling with the links provided, what I would suggest is don't worry about Object.Create. Also seen as your using the keyword `let`, it might also be worth you skipping classic JS functional constructor, and jumping into using the new `class` decorator, as it would make doing OOP a little easier to use. – Keith Oct 22 '17 at 21:38
  • Well, the use case that you present in your example won't benefit from `Object.create`… You're not even using prototypical inheritance anywhere here. – Bergi Oct 22 '17 at 22:04
  • "*If I have this code what would it look like as an Object.create and how could it be called upon?*" - the [last question you linked](https://stackoverflow.com/q/2709612/1048572) has quite literally the same example, just with an extra method on the instance. – Bergi Oct 22 '17 at 22:09

1 Answers1

0

Object.create() is not strictly a necessary part of JavaScript. It was added to alleviate the need to remember to use new and give us all a more explicit way to create instances that inherit from other objects.

Let's take your code:

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 developers are just supposed to know from the Pascal naming convention that the function is a constructor function and new should be used.

But, fundamentally, your code and Object.create() can both get you to the same result. It's just that Object.create() takes away the need for new and gives you a very explicit way to indicate what you are doing.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • I'd rather drop `new` than `Object.create` from the language. It's a much more important primitive. You can trivially derive a `new` function from it, but not so easy the other way round. – Bergi Oct 22 '17 at 22:07