home / blog / podcasts / videos / notes / photos / about / more

Call constructor with Object.create()

in JavaScript

Posted by Jeena

Yesterday I learned something new about JavaScript, how to use Object.create() and still call the constructor. We start with a Player object which we can instanciate

function Player(name) {
    this.name = name;

Player.prototype.sayName = function () {

Normally you would just do something like that:

var player1 = new Player("jeena");
// >> "jeena"

But if you want to use Object.create() to for example add a property just to this instance:

var player2 = Object.create(Player.prototype, {age: {value: 10}});
// >> 10

// >> undefined

That is not the desired behaviour, but I couldn't see how to call the constructor while using Object.create(). Luckyly I know people who know much about JavaScript so I got the tip from Tim on how to do it, he said: "Just call the constructor.". After much confusion I got an example and here it is:

Player.apply(player2, "peter");
// >> "peter"

The thing is that you can't do player2.apply() because player2 is not a function but a object. Player on the other hand is of type function, so you are able to call apply() on it and it will call the Player() constructor.

That wasn't that hard, was it? I always wondered why if you want to use call() or apply() you have to write player2.foo.call(player2, args) but now finally I understand that, the first player2 appearance is needed to get to the function (through the player2 object) and the second one is what will be "this" in the method/function. I should have looked up that way before on my own.

So now you know how to use Object.create() and still be able to call the constructor.

Have you written a response? Let me know the URL:

There's also indie comments (webmentions) support.