JavaScript: Call Any Function as Method

,

You can call a function with its this set to any object you want, even if the function is not a method of the object. You can do this by using the method “call” or “apply”.

ƒ.call(…)

f.call(obj, arg1, arg2, …) → evaluate function f(arg1, arg2, …) with function f's this keyword replaced by obj. ECMAScript §15#sec-15.3.4.4

Note: If f is a property of o, then f.call(o, args) is the same as o.f(args)

// example of using method ‹f›.call(‹o›)

function ff() {
    this["p"] = 4;
    return this;
}

var o1 = {"b":2};

ff.call(o1)

console.log( o1 );              // { b: 2, p: 4 }

ƒ.apply(…)

A similar method is “apply”. It's the same as “call”, but the second argument is a array. The elements of the array is passed to the function.

f.apply(obj) → evaluate function f() with function f's this keyword replaced by obj. ECMAScript §15#sec-15.3.4.3

f.apply(obj, arg array) → evaluate function f with function f's this keyword replaced by obj, and elements of the array arg array is passed to the function as arguments.

// example of using method 「‹f›.apply(‹o›,…)」

function ff(x,y,z) {
    this["x"] = x;
    this["y"] = y;
    this["z"] = z;
    return this;
}

var o1 = {"b":2};

ff.apply(o1,[7,8,9])

console.log( o1 ); // { b: 2, x: 7, y: 8, z: 9 }

〔☛ JavaScript: What's the value of 「this」 Keyword?

blog comments powered by Disqus