My Technical Notes

Thursday, 9 July 2015

JavaScript: defining the new operator in terms of apply/call

When `new`-ing up a function e.g:


function Person(forename, surname) {
    this.forename = forename;
    this.surname = surname;
}


var p = new Person("Tahir", "Hassan");
alert(p.forename); // Tahir
alert(p.surname); // Hassan

What happens is that a new object is created which `this` reference is set to. Therefore this new object will get its `forename` and `surname` properties set.

In JavaScript, we can call a function, and with setting the `this` reference to an object of our choosing:


var testObj = { }; // create an empty object
Person.call(testObj, "John", "Doe");
alert(testObj.forename); // John
alert(testObj.surname); // Doe

The `apply` function works exactly like `call` but it expects an array containing the arguments to the function rather "listing out" the arguments:


var testObj = { }; // create an empty object
Person.apply(testObj, ["Jane", "Doe"]);
alert(testObj.forename); // Jane
alert(testObj.surname); // Doe

What we can surmise is that `new` creates an empty javascript object `{ }`, and then uses `apply` with the empty javascript object as the argument like so:


function New(type, args) {
    var obj = {};
    type.apply(obj, args);
    return obj;
}

var p = New(Person, ["Steve", "Jobs"]);
alert(p.forename) // Steve
alert(p.surname) // Jobs

No comments: