omega omega - 26 days ago 5x
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
, such that it passes the variable
into foo as the
variable, and the string
for the parameter
, so it logs this

hello world



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

In, 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);.[, arg1[, arg2[, ...]]])

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

var e = "world";, '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.