0

Why is it possible to do Object.create directly on an object:

const greet = {
    name: null
}
let s = Object.create(greet);

But you cannot do that directly on a function, and must add in the .prototype of it.

function greet(name) {
    this.name = name;
}
let s = Object.create(greet.prototype);

Why is one allowed but the other is not?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 1
    You can derive an object from a function [as well](https://jsfiddle.net/2vmdzyqo/) (the resulted object is not a function, though). `Object.create` takes a prototype (any object) as an argument, and makes [[Prototype]] of it for the newly-created function. But, [`Object.create`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) doesn't call any constructors and it doesn't assign any own properties, unless you're specifically passing those properties. – Teemu Feb 01 '22 at 19:58
  • "*But you cannot do that directly on a function*" - sure you can, every function is an object, you can write `Object.create(greet)` just fine. It might not do what you want though – Bergi Feb 01 '22 at 19:59
  • @Bergi I see -- so why wouldn't the direct way of `Object.create(greet)` not do what we want it to do? – samuelbrody1249 Feb 01 '22 at 19:59
  • @samuelbrody1249 Well I don't actually know what you *want* to do, all I can tell is that it would have a different result than your first snippet or `Object.create(greet.prototype)` – Bergi Feb 01 '22 at 20:01
  • @Bergi basically just emulating a class keyword. – samuelbrody1249 Feb 01 '22 at 20:03
  • 2
    @samuelbrody1249 Do you understand how prototype inheritance works? Why classes (i.e. constructors) have a `.prototype` and how that interacts with `new`? What `Object.create` does? – Bergi Feb 01 '22 at 20:07
  • Take a look at [this answer](https://stackoverflow.com/a/572996/1169519). – Teemu Feb 01 '22 at 20:11

0 Answers0