Javascript Quiz
有段时间没来冒泡了,前些天,同事发了一个JavaScript Quiz的链接,也解答了一下,下面贴出相应的题目及解答思路。顺便祝大家圣诞快乐!
1.
(function(){
return typeof arguments;
})();
A “object”
B “array”
C “arguments”
D “undefined”
答案为:A
arguments是由控制器进入到function执行环境时创建的对象,其[[prototype]]为Object.prototype,参见ES262-3 10.1.6
2.
var f = function g(){ return 23; };
typeof g();
A “number”
B “undefined”
C “function”
D Error
答案为:D和A都可以,需要区别浏览器,如果按照ES262的标准实现,应该是D
参见:ES262-3 13 Note
http://www.jslab.org.cn/?tag=FunctionDeclarationaAndFunctionExpression
3.
(function(x){
delete x;
return x;
})(1);
A 1
B null
C undefined
D Error
答案为:A
参见ES262-3
11.4.1, The delete Operator, If Type(Evaluate(UnaryExpression)) is not Reference, return true.
8.7, A Reference is a reference to a property of an object. A Reference consists of two components, the base object and the property name.
附加信息:
8.6.1, DontDelete, Attempts to delete the property will be ignored. See the description of the delete operator in section 11.4.1.
10.1.6,活动对象中的arguments属性为{DontDelete}
4.
var y = 1, x = y = typeof x;
x;
A 1
B “number”
C undefined
D “undefined”
答案为:D
这里容易将C和D搞混,首先,理解var的预编译,所有var声明会在控制器进入到执行环境时做的第一步事情,创建活动对象时进行处理,对应值都为undefined,接下来才是赋值操作.
var y = 1, x = y = typeof x;等同于
var y,x;
y=1;x=(y = typeof x);前面的y=1;可以忽略,所以只剩下x = (y = typeof x);
x为undefined,经过typeof运算后,返回"undefined", typeof运算符返回结果都为string类型
参见:ES262-3 11.4.3
5.
(function f(f){
return typeof f();
})(function(){ return 1; });
A “number”
B “undefined”
C “function”
D Error
答案为:A
作用域问题,标识符查找的顺序,控制器进入函数时,活动对象将创建,arguments对象和其他声明都会被初始化到该对象,该活动对象会被插入到作用域链的顶端。
参见:ES262-3 10.2.3
6.
var foo = {
bar: function() { return this.baz; },
baz: 1
};
(function(){
return typeof arguments[0]();
})(foo.bar);
A “undefined”
B “object”
C “number”
D “function”
答案为:A
this的标识问题,注意arguments[0]();其实就是要去执行function() { return this.baz; },此时,this为global Object,即window,而window上木有baz属性或变量。
参见:ES262-3 10.1.7 ~ 10.2.3