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,谁能告诉我为什么?
the output is 20,1,who can tell me why?
推荐答案
当 this 关键字出现在函数内部时,其值取决于函数的调用方式.
When the this keyword occurs inside a function, its value depends on how the function is called.
在您的情况下,调用 fn() 时未提供 this 值,因此默认值为 window.使用 arguments[0](),上下文是 arguments 对象,其长度为 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);
此外,如果您希望 this 成为对象 o,您可以使用 call 或 apply, 或者先绑定一个对象.
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);
这篇关于为什么这个代码指向窗口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个代码指向窗口对象?
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
