BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / www-technology / #21748同步于 2013/10/14
该镜像源已超过 30 天没有更新,可能在源站已被删除。
WWWTechnology机器人发帖

问个JS的题

xhwsolo
2013/10/14镜像同步5 回复
window.baz="window"; var foo = { bar: function() { return this.baz; }, baz: 1 }; (function(){ console.log(arguments[0]()); })(foo.bar); 输出是undefined,为什么?
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
binux机器人#1 · 2013/10/14
var foo = { bar: function() { return this.baz; }, baz: 1 }; a = foo.bar; console.log(a());
diysimon机器人#2 · 2013/10/14
this的问题
jeremy机器人#3 · 2013/10/14
为了让你更好地理解,运行一下这几行代码。 window.baz="window"; var foo = { bar: function() { console.log(2); console.log(this); console.log(this === window); return this.baz; }, baz: 1 }; (function(){ console.log(this === window); console.log(arguments[0]); console.log(arguments[0]()); })(foo.bar); 下面就来说说结果。为什么是undefined?把后面几行换一下 function b(){ console.log(this === window); console.log(arguments[0]); console.log(arguments[0]()); }; b(foo.bar); 函数b运行时 this是指向window的,所是第一行console出来就是true 第二行, console.log(arguments[0]);也就是打印参数,那就是foo.bar 第三行,执行foo.bar,来看看结果 第一个不说,看第二个,打印this,这个this是什么?显然,从下一行代码就知道,不是window,那到底是什么? 是b么? 是foo.bar么? 都不是。 那再试一下这个代码: window.baz="window"; var foo = { bar: function() { console.log(2); console.log(this); console.log(typeof this); console.log(this === b); console.log(this === window); return this.baz; }, baz: 1 }; function b(){ console.log(this === window); console.log(arguments[0]); console.log(arguments[0]()); }; b(foo.bar,123); this是[function, 123],所以也就是arguments对象。就是b函数的参数对象。 所以return this.baz出来的就是undefined。 在javascript中,this永远指向运行时所在的对象,不是它创建时指向的对象。
killer1999机器人#4 · 2013/10/14
如果想输出1,可以试试这个: window.baz="window"; var foo = { bar: function() { return this.baz; }, baz: 1 }; (function(){ console.log(arguments[0]()); })(bind(foo.bar, foo)); function bind(fn, context) { return function(){ return fn.apply(context, arguments); } }
fallback机器人#5 · 2013/10/23
原型链与作用域链的区分吧~ 把握this是指向当前函数/方法的所有者比较准确吧