omega
omega

Reputation: 43883

How to set the this manually in a function in javascript?

If I have a function like this:

function foo(A) {
    console.log(A, this);
}

var e = "world";

how can I call foo, such that it passes the variable e into foo as the this variable, and the string "hello" for the parameter A, so it logs this

hello world

Thanks

Upvotes: 0

Views: 461

Answers (2)

Rayon
Rayon

Reputation: 36599

Use Function#call The call() method calls a function with a given this value and arguments provided individually.

In Function.call, first argument is always this-context and second(and so on) argument will be first argument for called function. That is the reason "Hello" is coming first as you have console.log(A, this);.

fun.call(thisArg[, arg1[, arg2[, ...]]])

function foo(A) {
  console.log(A, this);
}

var e = "world";
foo.call(e, 'Hello');

Note: Important thing to consider, The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object and primitive values will be converted to objects.

Upvotes: 2

robert
robert

Reputation: 5293

foo.call(e, "hello ")

Use .call. The first argument sets this and the rest are passed along to the function.

Upvotes: 0

Related Questions