0

I am kinda new to JavaScript, so was just learning about "this" pointer, I tried to use the apply() to change the context of an object, I ran the code in NodeJS REPL, and the output was undefined and undefined.

    var word="Hello";
    var obj={word:"GB"};
    function foo(){return this.word;}
    console.log(foo());
    foo.apply(obj);
    console.log(foo());

And I ran the same in chrome browser, It output Hello and Hello, using apply(), the output was supposed to be Hello and GB.

enter image description here

I am confused about this usage. Please help.

BenG
  • 14,826
  • 5
  • 45
  • 60
  • Doesn't matter how many times you execute `foo()` (including via `foo.apply(obj)`), you never change the value of `this.word` so why should it return anything different? – Phil Jun 16 '16 at 07:18
  • this.obj.word will give you what you desire! – sathya Jun 16 '16 at 07:19
  • 1
    I think your confusion comes from a misunderstanding about [`Function.prototype.apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). I suggest you read the documentation carefully and try `console.log(foo.apply(obj))` – Phil Jun 16 '16 at 07:20
  • To learn more about how the `this` keyworkd works in js, read https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/ch2.md by kyle simpson. – Arnelle Balane Jun 16 '16 at 07:20

2 Answers2

1

console.log the value after you call function using Function.apply as you are providing this context while invoking the function using .apply(CONTEXT).

foo.apply(obj); will not save the this context for the later invokation of foo

var word = "Hello";
var obj = {
  word: "GB"
};

function foo() {
  return this.word;
}
console.log(foo());
console.log(foo.apply(obj));

You can use .bind and keep the reference in a variable so that referred function will always have the binded-context

var word = "Hello";
var obj = {
  word: "GB"
};

function foo() {
  return this.word;
}
console.log(foo());
var bar = foo.bind(obj);
console.log(bar());
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

foo.apply(obj) indeed returns "GB", but you are passing foo() to console.log

perhaps you have mistaken apply with bind?

console.log(foo()); // World
foo = foo.bind(obj);
console.log(foo()); // GB

or your way:

console.log(foo.apply(obj)); // GB
pwolaq
  • 6,343
  • 19
  • 45