my code is:
var length = 20;
function fn(){
console.log(this.length);
}
var o = {
length:10,
e:function (fn){
fn();
arguments[0]();
}
}
o.e(fn);
the output is 20,1
,who can tell me why?
my code is:
var length = 20;
function fn(){
console.log(this.length);
}
var o = {
length:10,
e:function (fn){
fn();
arguments[0]();
}
}
o.e(fn);
the output is 20,1
,who can tell me why?
When the
this
keyword occurs inside a function, its value depends on how the function is called.In your case,
fn()
is called without providing the a this value, so the default value iswindow
. Witharguments[0]()
, the context is thearguments
object, whose length is1
.The point is it does not matter where the function is called, but it matters how the function is called.
Further more, if you want
this
to be the objecto
, you could usecall
orapply
, orbind
an object first.Let's expand your code a little bit:
Demo: http://jsfiddle.net/ambiguous/Ckf2b/
Now we can see what
this
is (and thus wherethis.length
comes from) whenfn
is called. This gives me the following output:We also have three ways of calling the function
fn
:fn()
: just call it like any old function.fn.call(this)
: Usecall
to force a specific context (AKAthis
).arguments[0]()
: Callfn
through thearguments
object.When you say
fn()
, there is no explicit value ofthis
anywhere in sight so, in a browser, you getwindow
as yourthis
. The globalwindow
happens to have alength
property:That's where the zero (in my output) comes from, your
window.length
may be different.We call
e
aso.e(fn)
sothis
insidee
iso
, that's whato.e(...)
means (barring bound functions and related complexities). So thethis
infn.call(this)
iso
and that makesfn.call(this)
the same (more or less) aso.fn = fn; o.fn()
and we geto
and10
in the console. Notice that dot showing up again?The third one,
arguments[0]()
, contains a hidden dot asp = 'm'; o[p]
is (more or less) the same aso.m
soarguments[0]()
is likefn = arguments[0]; arguments.fn = fn; arguments.fn()
.