正文
5. 数组不是基础类型
typeof {} === 'object' // true
typeof 'a' === 'string' // true
typeof 1 === number // true
// 但是....
typeof [] === 'object' // true
如果要判断一个变量var是否是数组,你需要使用Array.isArray(var)。
6. 闭包
这是一个经典的JavaScript面试题:
const Greeters = []
for (var i = 0 ; i < 10 ; i++) {
Greeters.push(function () { return console.log(i) })
}
Greeters[0]() // 10
Greeters[1]() // 10
Greeters[2]() // 10
虽然期望输出0,1,2,...,然而实际上却不会。知道如何Debug嘛?
有两种方法:
使用let而不是var。备注:可以参考Fundebug的另一篇博客 ES6之"let"能替代"var"吗?
使用bind函数。备注:可以参考Fundebug的另一篇博客 JavaScript初学者必看“this”
Greeters.push(console.log.bind(null, i))
当然,还有很多解法。这两种是我最喜欢的!
7. 关于bind
下面这段代码会输出什么结果?
class Foo {
constructor (name) {
this.name = name
}
greet () {
console.log('hello, this is ', this.name)
}
someThingAsync () {
return Promise.resolve()
}
asyncGreet () {
this.someThingAsync()
.then(this.greet)
}
}
new Foo('dog').asyncGreet()
如果你说程序会崩溃,并且报错:Cannot read property 'name' of undefined。
因为第16行的geet没有在正确的环境下执行。当然,也有很多方法解决这个BUG!
我喜欢使用bind函数来解决问题: