omega omega - 2 months ago 7
Javascript Question

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

Answer

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.