user3057928
user3057928

Reputation: 633

object.create syntax usage in Javascript

var Parent = {};
var child = Object.create(parent);

is the above block of code as same as below?

var Parent = {};
var child = new Parent();

if not what the Object.create thingy do?

Upvotes: 0

Views: 56

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

is the above block of code as same as below?

No. Your second example causes a runtime error, because you're trying to call something as a function that isn't a function.

if not what the Object.create thingy do?

Object.create creates a new object setting the object you give it as the new object's prototype. Example:

var a = {foo: "bar"};
var b = Object.create(a);
console.log(b.foo);      // "bar", because `b` gets `foo` via its prototype
console.log("foo" in b); // true, because `b` gets `foo` via its prototype
console.log(b.hasOwnProperty("foo")); // false, the property is on its prototype

Object.create also has a second argument which allows you to define properties on the object you're creating, details on MDN and (of course) in the specification.


If you want to use new Xyz repeatedly to create objects that all share a common prototype and initialization (commonly called "classes" of objects, but that term is very loose in JavaScript), you do that by writing a function (called a "constructor function" when you use it with new) and assigning the things that the objects should share to YourFunction.prototype, which is what the new operator will assign to the objects as their prototype (like Object.create assigns the prototype from the argument you give it). E.g.:

function Thingy() {
}
Thingy.prototype.foo = "bar";

var a = new Thingy(); // 1. Creates new object
                      // 2. Assigns `Thingy.prototype` as the prototype
                      // 3. Calls Thingy with `this` referencing the new object
console.log(a.foo);   // "bar" because it gets it from its prototype

There are use cases for constructor functions, and there are use cases for using Object.create. The great thing about JavaScript is you have both.

Upvotes: 7

Related Questions