Javascript Call


Call() is an attached methods of all functions in javascript. Similar methods also include toString(), apply().

To be simple, call() can apply a method of an object to another object. In javascript, function, class are objects.

function add(x, y)
{
	alert(x + y);
}
function subtract(x, y)
{
	alert(x - y);
}
subtract.call(add,1,2); //Return -1



Here, subtract method is used for function add,
subtract.call(add,1,2) = subtract(1,2).

Let's see another example:

function class1()
{
	this.a = 7;
	this.foo = function()
	{
		alert(this.a * 10 - 8);
	}
}
function class2()
{
	this.a = 9;
}
var c1 = new class1();
var c2 = new class2();
c1.foo.call(c2); // = 9 * 10 - 8 = 82

Class class1 has foo() method, class2 does not. Here we used the foo() method of class1 for class2. It's like the friendship function in C++.

Call can be used to realize class inheritance:

function class1()
{
	this.a = 7;
	this.foo = function(b)
	{
		alert(this.a * b - 8);
	}
}
function class2()
{
	Class1.call(this);
}
var c2 = new class2();
c2.foo(2); // = 7 * 2 - 8 = 6


Similiar to call method, apply method can execute a method of an object for another object.

function add(x,y)
{
	alert(x+y);
}
function subtract(x,y)
{
	alert(x-y);
}
subtract.apply(add,[1,2]); //Return -1



Here, subtract method is used for function add,
subtract.apply(add,[1,2]) = subtract(1,2).

Let's see another example:

function archive(){
	this.a=7;
	this.foo=function()
	{
		var res=0;
		res = this.a * 10 - this.b;
		alert(res);
	};
}
function func(b){
	this.b=b;
	archive.apply(this,arguments);
}
var s1= new func(3);
s1.foo(); //=7 * 10 - 3 = 67;

Class class1 has foo() method, class2 does not. Here we used the foo() method of class1 for class2.

endmemo.com © 2024  | Terms of Use | Privacy | Home