RcBuilder@walla.com
call centre: 054-5614020

javascript apply and call

26
Jan
2016
Posted by: RcBuilder  /   Category: Array / class / function / JAVASCRIPT / Object   /   No Comments

javascript apply and call

apply

allows to call any function on any object,
parameters as array,
the caller object will serve as the context and we can reach it using the ‘this’ variable.

syntax:

[method].apply([caller], [param1, param2 ...]);

e.g:

function Person(name) {
this.name = name;
}

function doSomething(param1, param2) {
// this refer to the caller object
console.log(this.name + ‘ -> ‘ + param1 + ‘, ‘ + param2);
}

var person1 = new Person(‘Roby Cohen’);
var person2 = new Person(‘Avi Cohen’);

doSomething.apply(person1, ['hello', 'world']); // Roby Cohen -> hello, world
doSomething.apply(person2, [1000, 2000]); // Avi Cohen -> 1000, 2000

notice! the caller can be set as any object we’d like
var user = { id: 25, Name: ‘Roby Cohen’, Age: 35 };
fun.apply(user); // call to ‘fun’ function with ‘user’ context – ‘this’ variable will refer to the ‘user’ object
call

allows to call any function on any object,
parameters as comma-separated list.
the caller object will serve as the context and we can reach it using the ‘this’ variable.

syntax:

[method].call([caller], [param1], [param2] …);

e.g:

function Person(name) {
this.name = name;
}

function doSomething(param1, param2) {
// this refer to the caller object
console.log(this.name + ‘ -> ‘ + param1 + ‘, ‘ + param2);
}

var person1 = new Person(‘Roby Cohen’);
var person2 = new Person(‘Avi Cohen’);

doSomething.call(person1, ‘hello’, ‘world’); // Roby Cohen -> hello, world
doSomething.call(person2, 1000, 2000); // Avi Cohen -> 1000, 2000

notice! the caller can be set as any object we’d like
var user = { id: 25, Name: ‘Roby Cohen’, Age: 35 };
fun.call(user); // call to ‘fun’ function with ‘user’ context – ‘this’ variable will refer to the ‘user’ object

Author Avatar

About the Author

בניית אתרים ופתרונות טכנולוגים | RcBuilder

No Comments


  • פיתוח מערכות
  • פתרונות טכנולוגים
  • קידום אתרים
  • בניית אתרים