我的代码是:
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
.
With 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
or apply
, or 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)