Example #1: Function expression identifier leaks into an enclosing scope
實例1:函數表達式標示符滲進了外圍作用域
var f = function g(){};
typeof g; // "function"
Remember how I mentioned that an identifier of named function expression is not available in an enclosing scope? Well, JScript doesn't agree with specs on this one - g in the above example resolves to a function object. This is a most widely observed discrepancy. It's dangerous in that it inadvertedly pollutes an enclosing scope - a scope that might as well be a global one - with an extra identifier. Such pollution can, of course, be a source of hard-to-track bugs.
我剛才提到過一個有名函數表達式的標示符不能在外部作用域中被訪問。但是,JScript在這點上和標準并不相符,在上面的餓例子中g卻是一個函數 對象。這個是一個可以廣泛觀察到的差異。這樣它就用一個多余的標示符污染了外圍作用域,這個作用域很有可能是全局作用域,這樣是很危險的。當然這個污染可 能是一個很難去處理和跟蹤的bug的根源
Example #2: Named function expression is treated as BOTH - function declaration AND function expression
實例2:有名函數表達式被進行了雙重處理,函數表達式和函數聲明
typeof g; // "function"
var f = function g(){};
As I explained before, function declarations are parsed foremost any other expressions in a particular execution context. The above example demonstrates how JScript actually treats named function expressions as function declarations. You can see that it parses g before an “actual declaration” takes place.
正如我前面解釋的,在一個特定的執行環境中,函數聲明是在所有的表達式之前被解釋。上面的例子說明JScript實際上把有名函數表達式作為一個函 數聲明來對待。我們可以看到他在一個實際的聲明之前就被解釋了。
This brings us to a next example:
在此基礎上我們引入了下面的一個例子。
Example #3: Named function expression creates TWO DISCTINCT function objects!
實例3:有名函數表達式創建兩個不同的函數對象。
var f = function g(){};
f === g; // false
f.expando = 'foo';
g.expando; // undefined
This is where things are getting interesting. Or rather - completely nuts. Here we are seeing the dangers of having to deal with two distinct objects - augmenting one of them obviously does not modify the other one; This could be quite troublesome if you decided to employ, say, caching mechanism and store something in a property of f, then tried accessing it as a property of g, thinking that it is the same object you're working with.
在這里事情變得更加有趣了,或者是完全瘋掉。這里我們看到必須處理兩個不同的對象的危險,當擴充他們當中的一個的時候,另外一個不會相應的改變。如 果你打算使用cache機制并且在f的屬性中存放一些東西,只有有試圖在g的屬性中訪問,你本以為他們指向同一個對象,這樣就會變得非常麻煩
新聞熱點
疑難解答
圖片精選