0%

【JS】考題搜集

1.Which is false ?

1
2
3
4
(A) 1 == '1'
(B) NaN == NaN
(C) 1 == [1]+[]
(D) undefind === undefined

(B)

2.Please answer below two “this”?

1
2
3
4
5
6
$('#foo').on('click', function(e){
console.log( this );
setTimeout( function(){
console.log( this );
}, 1000}
})

假設是 jQuery 的前提下,
第一個 this 是 #foo ,因為 jQuery 是這樣設計的。
第二個 this 是 global (在 browser 環境下是 window )

3.What do you think foo() is ?

1
2
3
if(1) function foo(){ return 'a'}
else function foo(){ return 'b'}
console.log( foo() )

這題考得是 function scope ,這題就蠻有深度了。
答案是不管 if else 寫殺小,
function 都會定義,所以一定是 ‘b’。

跟這題對稱的題目是:

1
2
3
4
5
6
7
8
var foo ;
if(1) {
oo = function(){ return 'a'}
}
else {
foo = function(){ return 'b'}
}
console.log( foo() )

這時答案就會是 a

因為 function (){} 這種 pattern 會額外的開外掛,
所以一般我會建議大家寫後面這種。

4.Please explain what is the difference between “setTimeout()” and “setInterval()” ?

setTimeout(fn,duration) 是一次性的
setInterval(fn,duration) 是每隔 duration 會觸發的

5.Please explain what the use of “preventDefault()” and “”stopPropagation()” in Event Object ?

假設頁面是這樣:

1
2
3
<div id="p">
<a href="" id="a" target="_blank">link</a>
</div>

就以 a.onclick 來說明好了,點了一個超連結,
正常狀況下超連結會進行並開啟新頁,
p 的 onclick 會被觸發(因為事件向上傳遞)。

如果在 a.onclick 裡面下 preventDefault() ,
a 的超連結就不會打開頁面。

如果在 a.onclick 裡面下 stopPropagation(),
p.onclick 就不會觸發。

來源:
https://www.ptt.cc/bbs/Ajax/M.1371198760.A.DDB.html