Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2015年1月5日 D7 #36

Open
nunnly opened this issue Jan 5, 2015 · 2 comments
Open

2015年1月5日 D7 #36

nunnly opened this issue Jan 5, 2015 · 2 comments
Labels

Comments

@nunnly
Copy link
Owner

nunnly commented Jan 5, 2015

D7基础题了,新手们可以试试,大湿们也看看会不会掉坑。
晚上贴讲解

//请写出下面这一段的运行结果
var foo = {  
  bar: function() { return this.baz; },  
  baz: 1 
}; 

(function(){  
  return typeof arguments[0](); 
})(foo.bar);
@nunnly nunnly added the question label Jan 5, 2015
@nunnly
Copy link
Owner Author

nunnly commented Jan 6, 2015

"undefined"
为什么是"undefined"?.
我们必须要知道this运算符是怎么工作的.

JS语言精粹总结的很精炼:
1 纯粹的函数调用
2 作为对象方法的调用
3 作为构造函数调用
4 apply调用

我们看看题目是属于那种环境?
在arguments0中执行了一个方法,arguments[0]就是foo.bar方法
注意:这在foo.bar中的this是没有绑定到foo

虽然 foo.bar 传递给了函数,但是真正执行的时候,函数 bar 的上下文环境是 arguments ,并不是 foo
arguemnts[0] 可以理解为 arguments.0(不过写代码就不要这样了,语法会错误的),所以这样看来,上下文环境是 arguemnts 就没问题了,所以在执行baz的时候自然this就是window了,window 上没有baz属性,返回的就是undefined, typeof调用的话就转换成"undefined"了

附上博文
http://www.cnblogs.com/aaronjs/archive/2011/09/02/2164009.html

MDC
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/this_Operator#Description

还有一些与这有些类似的题目,请点击这里
http://www.cnblogs.com/aaronjs/p/3172112.html

@gggdandan
Copy link

(function(){
console.log(typeof arguments[0].call(foo));
})(foo.bar);

@nunnly nunnly added 难度7 and removed question labels Jan 23, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants