首先咱們來看一下題目,都各自思考一下,本身是否可以作出來。而後再跟後面的答案對比一下前端
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)
(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) {}
var log = console.log var hint = window.alert var write = document.write log('123') hint('123') wirte('123')
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)
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')
console.log(b.x) // {n:3} console.log(a.x) // undefined 這是跟js的優先級有關的 .的優先級最高,所以先計算左邊的b.x,a.x
(1) console.log(new Date() -start) // 不是必定500,而是大於等於500 主要是因爲定時器的時間不必定準,這個跟異步的機制有關 當定時器的時間到了以後,執行函數會進入棧中,會根據棧中的執行任務, 依次執行(不懂的能夠學習一下異步機制) (2) console.log(new Date() -start) // 大於等於1000 因爲是單線程
log('123') // 正常 hint('123') // 正常 write('123') // 報錯 這是因爲write是至關於window.write;而document.write下面應該會用到this對象, 因此會報錯 應當改爲window.write(document, '123')
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對象
script start async1 start async2 promise1 async1 end script end promise2 setTimeout 這一塊跟異步有關 先同步,後異步,在回調。還有promise機制