這邊列舉了5個前端典範的面試題
起首我們來看一下問題,都各自思索一下,本身是不是能夠做出來。然後再跟背面的答案對照一下
問題1
var a = {n:1}
var b = {n:2}
b.x = a = {n:3}
console.log(b.x)
a.x = a = {n:3}
console.log(a.x)
問題2
(1)
var start = new Date()
setTimeout(function() {
console.log(new Date() -start)
}, 500)
(2)
var start = new Date()
setTimeout(function() {
console.log(new Date() -start)
}, 500)
while((new Date() - start <= 1000) {}
問題3
var log = console.log
var hint = window.alert
var write = document.write
log('123')
hint('123')
wirte('123')
問題4
var name = 'A'
function getName() {
return this.name
}
var obj = {
name: 'B',
getName: function() {
return this.name
},
showName:function(a) {
console.log(getName())
console.log(a())
console.log(a === arguments[0])
console.log(arguments[0]())
}
}
obj .showName(getName, 1)
問題5
async function async1() {
console.log('async1 start')
await async2()
console.log('async1 end')
}
async function async2() {
console.log(async2())
}
console.log('script start')
setTimeout(function() {
console.log('setTimeout')
}, 0)
async1()
new Promise(function (resolve) {
console.log('promise1')
resolve()
}).then(function() {
console.log('promise2')
})
console.log('script end')
答案1
console.log(b.x) // {n:3}
console.log(a.x) // undefined
這是跟js的優先級有關的 .的優先級最高,因而先盤算左側的b.x,a.x
答案2
(1)
console.log(new Date() -start) // 不是肯定500,而是大於即是500
主如果因為定時器的時候不肯定準,這個跟異步的機制有關
當定時器的時候到了以後,實行函數會進入棧中,會依據棧中的實行任務,
順次實行(不懂的能夠進修一下異步機制)
(2)
console.log(new Date() -start) // 大於即是1000
因為是單線程
答案3
log('123') // 一般
hint('123') // 一般
write('123') // 報錯
這是因為write是相當於window.write;而document.write下面應該會用到this對象,
所以會報錯
應該改成window.write(document, '123')
答案4
console.log(getName()) // 'A' this === window
console.log(a()) // 'A' this === window
console.log(a === arguments[0]) // true
console.log(arguments[0]()) // undefined this 為argument對象
答案5
script start
async1 start
async2
promise1
async1 end
script end
promise2
setTimeout
這一塊跟異步有關
先同步,后異步,在回調。另有promise機制