The apply method in JavaScript

From LQWiki
Jump to navigation Jump to search

The apply() method takes two arguments: the object to be used for this and an array of arguments to be passed to the function. For example:

function sayColor(sPrefix, sSuffix) {
alert(sPrefix + this.color + sSuffix);
};
var obj = new Object();
obj.color = “red”;
//outputs “The color is red, a very nice color indeed. “
sayColor.apply(obj, new Array(“The color is “,”, a very nice color indeed.”));

This is the same example as before, but now the apply() method is being called. You can edit JavaScript code by JavaScript editor. When apply() is called, the first argument is still obj, which indicates that the this keyword in sayColor() should be assigned the value of obj. The second argument is an array consisting of two strings, which are matched up with the prefix and suffix arguments of sayColor(). This also results in the message “The color is red, a very nice color indeed.” being displayed. This method is also used in place of the three lines to assign, call, and delete the new method:

function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this, new Array(sColor));
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}

Once again, you pass this in as the first argument. The second argument is an array with just one value: color. You can, alternatively, pass in the entire arguments object of ClassB as the second argument of the apply() method:

function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this, arguments);
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}

Of course, passing in the object of the arguments only works if the order of the arguments in the superclass constructor is exactly the same as the order of the arguments in the subclass. When this is not the case, you must create a separate array to place the arguments into the correct order. You could also use the call() method.