This one made me smile.

In my most recent interview I was asked such a simple question, but it stumped me for a while.

Without using the new keyword, how could you create an instance of a class?

I audibly chuckled in the interview room. Of all the things to stutter on, this wasn’t what I would have expected.

I guess I’d taken new for granted. Probably one of the first interview questions in a long time that left me short for words.

Firstly, let’s take a look at our simple class, Person:

var Person = function(name) {
  this.name = name;
}

Pretty simple. Our Person class takes one paramter - name - and sets it to an object property.

This is how we might create an instance of Person:

var p = new Person('Dave');

console.log(p.name); // Prints 'Dave'.

So how could we rewrite our code to not use the new keyword. Well, we know that at the end of the object creation, the context of this needs to be bound to the new object that we have created. We also need access to all of our instance’s properties. We would also expect the instanceof Person check to return true. Lastly, we also need to be able to pass in parameters as part of calling the constructor of our object. If we can tick these boxes, we’ll be pretty happy.

How can we do this? Fortunately we can leverage the usefulness of the call() function. What does call() do? It allows us to call a function, while allowing us to specify what the current object is (i.e. can set the context of which the function was called). Therefore, we can create a new object with the internal Person prototype and use that as the context in which we want to invoke the call() function.

With this in mind, we can use the following code to insantiate our object.

// With `new`.
var p1 = new Person('Dave');

// Without `new`.
var p2 = Object.create(Person.prototype);
Person.call(p2, 'Alice');

// The results.
console.log(p1.name); // Prints 'Dave'.
p1 instanceof Person; // True.
console.log(p2.name); // Prints 'Alice'.
p2 instanceof Person; // True.

Neat!

I know that you’re probably thinking how useless this is, as it’d be weird if we constructed objects this way. However, understanding how this works and how we can maniupulate it demonstrates that we grasp the fundamental concepts of how JavaScript objects work.

Let me know if you have any thoughts or other ways to solve this problem.

-Dave