我的代码是:
var length = 20;
function fn(){
console.log(this.length);
}
var o = {
length:10,
e:function (fn){
fn();
arguments[0]();
}
}
o.e(fn);
输出结果是
20,1
,有谁能告诉我为什么?我的代码是:
var length = 20;
function fn(){
console.log(this.length);
}
var o = {
length:10,
e:function (fn){
fn();
arguments[0]();
}
}
o.e(fn);
20,1
,有谁能告诉我为什么?this
关键字出现在函数内部时,其值取决于调用该函数的方式。fn()
被调用时没有提供this值,因此默认值为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);
this
指向对象o
,您可以使用call
或apply
,或者先使用bind
绑定一个对象。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);
this
并不是上下文,它是执行上下文的一个组成部分(在ES5中称为词法环境)。你应该写成“在未提供this
值的情况下调用了fn()
函数”。将this
称为上下文会让人产生困惑。 - RobGfn();
时,它将是未定义的。 - xdazzvar length = 20;
function fn() {
console.log(this, this.length);
}
var o = {
length: 10,
e: function(fn) {
fn();
fn.call(this);
arguments[0]();
}
}
o.e(fn);
演示: http://jsfiddle.net/ambiguous/Ckf2b/
现在我们可以看到,当调用fn
时,this
指的是什么(因此this.length
来自哪里)。这给我以下输出:
DOMWindow 0
Object 10
[function fn() { console.log(this, this.length); }] 1
fn
的方式:
fn()
: 像任何普通函数一样直接调用。fn.call(this)
: 使用call
来强制指定上下文(即this
)。arguments[0]()
: 通过arguments
对象调用fn
。fn()
时,视野中没有明确的this
值,因此在浏览器中,您会得到window
作为您的this
。全局的window
恰好有一个length
属性:
这就是我的输出中的零(零可能会因您的返回窗口中帧(frame)或 iframe 元素(frame 或 iframe元素)的数量。
window.length
而异)。e
来调用o.e(fn)
,因此e
内部的this
是o
,这就是o.e(...)
的意思(除了绑定函数和相关复杂性)。因此,在fn.call(this)
中的this
是o
,这使得fn.call(this)
与o.fn = fn; o.fn()
大致相同,我们在控制台中获得了o
和10
。注意那个点再次出现了吗?
第三种方法
fn.call(o)
就像o.fn = fn; o.fn()
arguments[0]()
包含一个隐藏的点,因为p = 'm'; o[p]
(大致)等价于o.m
,所以arguments[0]()
就像fn = arguments[0]; arguments.fn = fn; arguments.fn()
。
call
和apply
的相关内容。 - mu is too shortfn()
和arguments[0]()
,一个调用了call
,另一个调用了apply
吗? - McGarnaglethis === window
,在第二个中this===arguments
。 将console.log更改为console.log(this.length, this);
并将其调用为o.e(fn,'test');
然后您会看到您得到的参数数组。 - somethis
来执行fn()
。arguments[0]()
之所以表现出它的行为,是因为有一个隐藏的点,所以它有点像说arguments.0()
(如果后者当然是有效的JavaScript)。 - mu is too short