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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…