JS筆試題

來源:互聯網
上載者:User

標籤:c   a   ext   使用   資料   cti   

1,考察this


var length = 10
function fn(){
alert(this.length)
}
var obj = {
length: 5,
method: function(fn) {
fn() // ?
arguments[0]() // ?
}
}
obj.method(fn)
這裡的坑主要是arguments,我們知道取對象屬於除了點操作符還可以用中括弧,這裡fn的scope是arguments,即fn內的this===arguments,調用時僅傳了一個參數fn,因此length為1。

 

2,函數運算式具名(函式宣告同時賦值給另一個變數)或函式宣告立即執行時,名僅在該函數內可訪問


~function() {
alert(typeof next) // ?
~function next() {
alert(typeof next) // ?
}()
}()
外層匿名函數自執行,列印next,接著內層具名函數自執行。會發現具名的next僅在其自身函數體內可訪問,即輸出為function。外面是不可見的,typeof就為undefined了。(註:此題IE6/7/8中輸出為function function, 標準瀏覽器為undefined function)

同樣的情況也發生在將具名函數賦值給一個變數時,如下

var func = function a() {
alert(typeof a)
}
func() // ?
alert(typeof a) // ?
這條規則是標準中(ES3/ES5)都已明確指出,但IE6、7、8沒有嚴格遵從。可參見w3help的分析或李松峰老師的翻譯《命名函數運算式探秘》

 

 

3,給基本類型資料添加屬性,不報錯,但取值時是undefined

a = 3
a.prop = 4
alert(a + a.prop) // ?
變數a為數字3,給其添加prop屬性,值為4(奇怪吧在JS中這是允許的,且不會有語法錯誤)。然後alert出a+a.prop的結果。結果是NaN。a.prop為undefined,3+undefined為NAN。

舉一反三,給字串添加屬性

str = ‘a‘
str.prop = ‘b‘
alert(str + str.prop) // ?
結果呢?

 

4,隱式的全域變數

var a = 1
function func() {
a = b = 2
}
func()
alert(a)
alert(b) // ?
JS中不用var聲明的變數預設是全域變數,而這裡的連等使的情況更加隱蔽。這裡的b是全域的,因此func外可以訪問。

 

5,變數聲明早於代碼運行(Scoping and Hoisting)


var uname = ‘jack‘
function change() {
alert(uname) // ?
var uname = ‘lily‘
alert(uname)
}
change()
這裡容易犯迷糊的是第一個alert,如果認為函數change外已經聲明賦值了,此時應該是jack,實際函數內又var了一次(雖然var在其後),預解析時仍然會將其置undefined。這也是為什麼書裡都建議變數聲明都放在代碼塊的最前面。

 

6,函式宣告早於變數聲明


function change() {
alert(typeof fn) // ?
function fn() {
alert(‘hello‘)
}
var fn
}
change()
change內先alert出fn,後函式宣告,再變數聲明。如果fn沒有函式宣告而僅是變數聲明,那麼結果與5一樣是undefined。但這裡卻是function。即同一個範圍內,函式宣告放在代碼塊後面和前面都沒有關係,函數可以正常使用。而變數聲明則需先置前,先使用則是undefined。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.