为什么代码会指向window对象
why the code this point to window object?
我的代码是:
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);
让我们稍微扩展一下您的代码:
var 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元素)。
这就是零(在我的输出中)的来源,你的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()
。
- 如何绑定“;这个“;在$http.post中->在AngularJS中解析/拒绝?(现在this=Window对象
- 为什么代码会指向window对象
- JavaScript Window 对象始终可访问
- 在window.onload之前/之后创建对象之间的区别
- 如何获取window.getSelection()的范围对象
- 未捕获的类型错误:属性'$'对象[object Window]的
- MS Edge有一个window.chrome对象??破坏浏览器检测
- 迭代窗口对象时出现“'window.webkitStorageInfo' is deprecated”警
- 哪个类等效于 GWT 中 Javascript 的对象 window.document
- 为什么这里的构造函数中的“this”总是“Window”对象
- 为什么“this”是这个JavaScript中的Window对象
- $window对象在其他模块中不可用
- 为什么要在 Window 对象中将全局声明变量的值设置为相同的值
- Chrome 16中的空白页中没有Window对象
- 为什么打印window对象而不是date对象?
- 框架B中的脚本不能引用框架A的Window对象
- 如何使用angular$window对象访问全局javascript方法
- 如何制作Facebook登录按钮's的onligin调用了一个不在window对象中的函数
- this 变量是 Window 对象,或者在 then 方法的 promise 中未定义
- Angularjs ui-gmap-window对象数据不渲染