Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:Function:call

From MDC


Contents

[edit] Summary

Allows you to call (execute) 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 = fun.call(thisArg[, arg1[, arg2[, ...]]]);

[edit] Parameters

thisArg 
Determines the value of this inside fun. If thisArg is null or undefined, this will be the global object. Otherwise, this will be equal to Object(thisArg) (which is thisArg if thisArg is already an object, or a String, Boolean, or Number if thisArg is a primitive value of the corresponding type). Therefore, it is always true that typeof this == "object" when the function executes.
arg1, arg2, ... 
Arguments for the object.

[edit] Description

You can assign a different this object when calling an existing function. this refers to the current object, the calling object.

With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

[edit] Examples

[edit] Example: Using call to chain constructors for an object

You can use call 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.

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.call(this, name, value);
}

prod_dept.prototype = new product();

// since 5 is less than 1000, value is set
cheese = new prod_dept("feta", 5, "food");

// since 5000 is above 1000, value will be 999
car = new prod_dept("honda", 5000, "auto");

[edit] See Also

apply