为什么代码这个指向window对象?

art*_*twl 4 javascript arguments this

我的代码是:

var length = 20;
function fn(){
    console.log(this.length);
}

var o = {
    length:10,
    e:function (fn){
       fn();
       arguments[0]();
    }
}

o.e(fn);
Run Code Online (Sandbox Code Playgroud)

输出是20,1谁,谁能告诉我为什么?

xda*_*azz 6

this关键字出现在函数内部时,其值取决于函数的调用方式.

在您的情况下,fn()调用时不提供此值,因此默认值为window.使用arguments[0](),上下文是arguments对象,其长度为1.

关键是调用函数的位置并不重要,但重要的是如何调用函数.

var length = 20;
function fn(){
    console.log(this.length);
}

var o = {
    length:10,
    e:function (fn){
       fn(); // this will be the window.
       arguments[0](); // this will be arguments object.
    }
}

o.e(fn);
Run Code Online (Sandbox Code Playgroud)

此外,如果您想this成为对象o,可以先使用callor applybind对象.

var length = 20;
function fn(){
    console.log(this.length);
}

var o = {
    length:10,
    e:function (fn){
       var fn2 = fn.bind(this);
       fn.call(this); // this in fn will be the object o.
       fn.apply(this); // this in fn will be the object o.
       fn2(); // this also will be the object o.
    }
}

o.e(fn);
Run Code Online (Sandbox Code Playgroud)