Skip to content Skip to sidebar Skip to footer

Setting The Value Of `this` With `apply()`

I don't understand why this code logs 'Hello world': var log = function(){ console.log(this) } var greeting = function(){ return 'Hello world' } greeting.apply(log) From what I ga

Solution 1:

From what I gather from the MDN page on apply(), calling apply(log) on greeting() sets greeting()'s this to log(), is that right?

No, not really. It sets sets greeting's this to log ... without the parentheses. So log will never get called.

Additionally, apply also executes the function it is called on. So in your case, greeting.apply(log) just executes the function greeting and sets this for this function to log. But since you don't use this within greeting it doesn't even matter what this is.

Solution 2:

I thought i would expand my comment with an answer. Javascript's apply and call are both methods of Function.prototype to set the context of the keyword this to a given object.

For Example.

var log = function() { console.log(this); };
 log() // this would `console.log` window or the global object
 log.call({example: "value"}); // Object {example: "value"}
 log.apply({example: "value"}) // same thing, but you can pass an array of arguments

Post a Comment for "Setting The Value Of `this` With `apply()`"