0

This there a way to pass a arbitrary value to "this" in the foo function below;

function foo(a){
var getThis = this;
var getA = a;

console.log("getThis:"+getThis);
console.log("\n"+a);
}

foo(5);

Expected output:

getThis: some value that I can pass
5

Answere to the question:

foo.call('some value that I can pass', 5);

thanks

patz
  • 1,306
  • 4
  • 25
  • 42
  • 1
    `foo.call(42, 5)`. But, just because you can does not mean you should. – zerkms Sep 08 '16 at 20:28
  • So you got your answer. Question is, why would you want that? That's what *arguments* are for – Amit Sep 08 '16 at 20:31
  • @Amit Well now you're getting pretty conceptual. Why does `this` exist at all? – 4castle Sep 08 '16 at 20:33
  • @Amit it's a perfectly valid thing to do, though. After all, `Array.prototype.slice.call(arguments)` is idiomatic JavaScript and it leverages changing the the context of the `slice` method. It's also why `.bind` exists and that was added due to popular demand. People _want_ to change `this` around. – VLAZ Sep 08 '16 at 20:36
  • @Amit I was writting a unit test of a function which only tests the function correctly if "this" has some predefined values – patz Sep 08 '16 at 20:36
  • 1
    Please don't edit the question to add the answer to it. Answers should be in answers. – Heretic Monkey Sep 08 '16 at 20:43

2 Answers2

2

Call the function using apply or call instead of calling it directly.

foo.call("this is a string", 5);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You can read more about this here MDN. You can call the function with different this in the following way:

foo.call("hello", 5);

foo.apply("hello", [5]);
Emil A.
  • 3,387
  • 4
  • 29
  • 46