Call and Apply properties

Call and Apply properties

by Nirvanachain

JavaScript

var x, o1, o2, r1, r2, r3;

x = 4;

o1 = {
    x : 2
};

o2 = {
    x : 7
};

function foo(m, n) {
    console.log('m = ', m);
    console.log('n = ', n);
    console.log('this.x = ', this.x);
    return console.log(m * n * this.x); 
};

r1 = foo(3, 1); //logs: m = 3, n = 2, this.x = undefined, NaN
r2 = foo.call(o1, 3, 1); //logs: m = 3, n = 1, this.x = 2 (.call() makes o1 now 'this'), 6
r3 = foo.apply(o2, [3, 1]); //logs: m = 3, n = 1, this.x = 7 (.apply() makes o2 now 'this'), 21