1.
http://www.jsforest.org/2010/07/29/js-this指向的小測試/
這個說是在考this的指向,實際上是在考變量的作用域。
先說其中第二題。o是一個對象,doIt是它的方法,那么doIt的this自然指向o
第二題結果為10無懸念。
再來看第一題,在doIt的內部加入了一個setTimeout方法,setTimeout又調用了一個匿名方法。
在javascript中,函數(shù)(或方法)也是對象,那么匿名方法中的this應該指向doIt,結果為20.
實際上將代碼跑了下,第一題結果為5.哪里錯了?
問題出在setTimeout。
window.setTimeout(code, delay)
When
code is executed, it is executed in the context of the Window object. If
code is a function, the Window object is the value of the
this keyword. If
code is a string, it is evaluated in the global scope with the Window object as the only object on the scope chain. This is true even if the call to
setTimeout( ) occurred within a function with a longer scope chain.
這段話說明了setTimeout不管在哪里執(zhí)行,其作用域都是在Window下,this一直指向Window。
第一題的x=5是全局變量,Window作用域下的。
這題說是在考this的指向,原來最終考的是個setTimeout的問題……被耍了
2.
http://www.css88.com/archives/2429
看到這個問題,首先注意到的是第一個用了
===,第二個沒有,而javascript是個弱類型語言,使用provisionalTable[item]取值沒判斷類型。
然后,試著找了Object中判斷值是否存在的方法,譬如provisionalTable.item ,in等都沒判斷類型。
想法一,重載[]方法,不過,這個怎么重載?又不是個function
想法二,數(shù)字是利用toString()轉成字符串的,那么重載Number.prototype.toString=function(){return this;}; 6=='6'返回false了,但provisionalTable[item]取值還是一樣
想法三,provisionalTable同時存在6和'6'時,provisionalTable[item]能區(qū)分這兩者,那么在provisionalTable中加入一個設為true時,將另一個也加入,并設為false。但這樣會有效率問題,事實上,acsu提出的方法里僅僅加了個typeof方法,就將效率損失殆盡。
突然想到,這個問題不是找解決方法,而是找最優(yōu)方法
嗯,作罷,效率問題不是我等小民該考慮的,這個必須從根本上重構javascript才行
不過思考下,還是能學到很多東西的