...

/

Calling the Constructor with the Apply Function

Calling the Constructor with the Apply Function

Learn how to use the Apply function with constructors.

We'll cover the following...

When calling the original constructor, we pass in the first two original arguments:

var NewConstructor = function(){
var obj = new OldConstructor(arguments[0], arguments[1]);
// code truncated for brevity
};
Passing the original arguments (assets/js/apps/config/storage/localstorage.js)

We can get away with this because we know exactly how our configureStorage function will be used—to configure local storage for models and collections. Luckily, both have two arguments in their constructor signature, so passing on two arguments to the original constructor will always work as expected.

Passing an arbitrary number of arguments

However, what if we wanted our code to work with an arbitrary number of arguments? JavaScript defines apply, which essentially enables us to call a function in such a way that a particular function is called with particular arguments.

For example, let’s say we want to call the ...