JavaScript是一门奇怪的语言,要真正掌握并不容易。废话很少说,来一个快速测试,5道题目,看看你对JavaScript是否真正掌握。准备好了吗?开始咯😄javascript
if (!("a" in window)) {
var a = 1;
}
console.log(a);复制代码
var a = 1,
b = function a(x) {
x && a(--x);
};
console.log(a);复制代码
function a(x) {
return x * 2;
}
var a;
console.log(a);复制代码
function b(x, y, a) {
arguments[2] = 10;
console.log(a);
}
b(1, 2, 3);复制代码
function a() {
console.log(this);
}
a.call(null);复制代码
题目来自👉dmitry.baranovskiy.com/post/914032…
解析加上了本身的理解😄前端
在浏览器环境中,全局变量都是window
的一个属性,即var a = 1
等价于 window.a = 1
。in
操做符用来判断某个属性属于某个对象,能够是对象的直接属性,也能够是经过prototype
继承的属性。
再看题目,在浏览器中,若是没有全局变量 a
,则声明一个全局变量 a
(ES5没有块级做用域),而且赋值为1。不少人会认为打印的是1。非也,你们不要忘了变量声明会被前置!什么意思呢?题目也就等价于java
var a;
if (!("a" in window)) {
a = 1;
}
console.log(a);复制代码
因此其实已经声明了变量a
,只不过if
语句以前值是undefined
,因此if
语句压根不会执行。
最后答案就是 undefined
git
这道题有几个须要注意的地方:github
console.log('b', b); // b undefined
var b = function() {}
console.log('b', b); // b function () {}复制代码
2.具名的函数表达式的名字只能在该函数内部取到,举个例子(排除老的IE😂):浏览器
var foo = function bar () {}
console.log('foo', foo);
// foo function bar(){}
console.log('bar', bar);
// Uncaught ReferenceError: bar is not defined复制代码
综合这两点,再看题目,最后输出的内容就为 1babel
函数声明会覆盖变量声明,但不会覆盖变量赋值,举个栗子简单粗暴:函数
function foo(){
return 1;
}
var foo;
console.log(typeof foo); // "function"复制代码
函数声明的优先级高于变量声明的优先级,但若是该变量foo
赋值了,那结果就彻底不同了:post
function foo(){
return 1;
}
var foo = 1;
console.log(typeof foo); // "number"复制代码
变量foo
赋值之后,变量赋值初始化就覆盖了函数声明。这个须要注意
再看题目测试
function a(x) {
return x * 2;
}
var a;
console.log(a); // function a(x) {...}复制代码
这题考察 arguments
对象的用法(详看👉JavaScript中的arguments对象)
通常状况,arguments
与函数参数是动态绑定关系(为何说是通常稍后会解释),因此很好理解,最后输出的是10
可是可是可是,咱们不要忘了一个特殊状况--严格模式,在严格模式中 arguments
与至关于函数参数的一个拷贝,并无动态绑定关系,举个栗子:
'use strict'
// 严格模式!!
function b(x, y, a) {
arguments[2] = 10;
console.log(a);
}
b(1, 2, 3); // 3复制代码
function a() {
console.log(this);
}
a.call(null);复制代码
关于 a.call(null);
根据ECMAScript262规范规定:
若是第一个参数传入的对象调用者是null
或者undefined
的话,call
方法将把全局对象(浏览器上是window
对象)做为this的值。因此,无论你何时传入null
或者 undefined
,其this
都是全局对象window
。因此,在浏览器上答案是输出 window
对象。
可是可是可是,咱们依旧不能忘记一个特殊状况--严格模式,在严格模式中,null
就是 null
,undefined
就是 undefined
,举个栗子:
'use strict';
// 严格模式!!
function a() {
console.log(this);
}
a.call(null); // null
a.call(undefined); // undefined复制代码
window
,Node.js中是global
;'use strict';
GitHub: 👉github.com/microzz
我的网站: 👉microzz.com/