Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 gather from the MDN page on apply(), calling apply(log) on greeting() sets greeting()'s this to log(), is that right? If that's so, why does the above code log "Hello world"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

this is a pseudo-parameter, it is passed to the function every time the function is called.

var person1 = { name: "John" }, person2 = { name: "Maria" };

function f (greeting) { return greeting + ", my name is " + this.name; }

f.apply(person1, ["hi"]) // "hi, my name is John"
f.apply(person2, ["hello"]) // "hello, my name is Maria"

So what happens when you call it normally, like foo(); ?
Well, it depends, on whether you're using "strict mode" or not:

  • when NOT using "strict mode", the function will receive the global object (window) as this.
  • when using "strict mode", the function will receive undefined as this.

To adapt your example:

var log = function(){ return "this is log func";  }   
var greeting = function(){ return "Hello world: " + this(); }
greeting.apply(log) // "Hello world: this is log func"

The above example works, because this is set to the log function. Since this is actually log, you can play around like you are doing with any other function:

var log = function(){ return "this is " + this.name;  }   
var greeting = function(){ return "Hello world: " + this.apply({name: "Mark"}); }
greeting.apply(log) // "Hello world: this is Mark

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...