为什么code这点窗口对象? [英] why the code this point to window object?
问题描述
我的code是:
var length = 20;
function fn(){
console.log(this.length);
}
var o = {
length:10,
e:function (fn){
fn();
arguments[0]();
}
}
o.e(fn);
输出 20,1
,谁可以告诉我为什么吗?
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.
在你的情况, FN()
调用时没有提供一个这个值,所以默认值为窗口
。
随着参数[0]()
,上下文是参数
对象,其长度为 1
。
In your case, fn()
is called without providing the a this value, so the default value is window
.
With arguments[0]()
, the context is the arguments
object, whose length is 1
.
的一点是没关系的其中的函数被调用,但它很重要的函数是如何叫
The point is it does not matter where the function is called, but it matters how the function is called.
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);
更进一步,如果你想这个
为对象 0
,你可以使用呼叫
或适用
或绑定
的对象第一位。
Further more, if you want this
to be the object o
, you could use call
or apply
, or bind
an object first.
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);
这篇关于为什么code这点窗口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!