Core JavaScript 1.5 Reference:Global Objects:Function:apply
From MDC
Contents |
[edit] Summary
Allows you to apply a method of another object in the context of a different object (the calling object).
| Method of Function | |
| Implemented in: | JavaScript 1.3 |
| ECMA Version: | ECMA-262 Edition 3 |
[edit] Syntax
var result = function.apply(thisArg[, argsArray]);
[edit] Parameters
-
thisArg - Determines the value of
thisinsidefun. IfthisArgisnullor undefined,thiswill be the global object. Otherwise,thiswill be equal toObject(thisArg)(which isthisArgifthisArgis already an object, or aString,Boolean, orNumberifthisArgis a primitive value of the corresponding type). Therefore, it is always true thattypeof this == "object"when the function executes.
-
argsArray - An argument array for the object, specifying the arguments with which
funshould be called, ornullor undefined if no arguments should be provided to the function.
[edit] Description
You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
apply is very similar to call, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With apply, you can use an array literal, for example, fun.apply(this, [name, value]), or an Array object, for example, fun.apply(this, new Array(name, value)).
You can also use arguments for the argArray parameter. arguments is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.
[edit] Examples
[edit] Example: Using apply to chain constructors
You can use apply to chain constructors for an object, similar to Java. In the following example, the constructor for the product object is defined with two parameters, name and value. Another object, prod_dept, initializes its unique variable (dept) and calls the constructor for product in its constructor to initialize the other variables. In this example, the parameter arguments is used for all arguments of the product object's constructor.
function product(name, value)
{
this.name = name;
if (value > 1000)
this.value = 999;
else
this.value = value;
}
function prod_dept(name, value, dept)
{
this.dept = dept;
product.apply(this, arguments);
}
prod_dept.prototype = new product();
// since 5 is less than 1000 value is set
var cheese = new prod_dept("feta", 5, "food");
// since 5000 is above 1000, value will be 999
var car = new prod_dept("honda", 5000, "auto");