Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - 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 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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...