2011-02-02 18 views
6
> (function() { return this; }).call(false) 
false 

> !!(function() { return this; }).call(false) 
true 

फ़ायरफ़ॉक्स 4 बीटा और क्रोम दोनों में विचित्र व्यवहार की व्याख्या करें।कृपया .call (झूठी)

ऐसा लगता है ... एक बूलियन कब, बुलियन नहीं है?

+0

मुझे यह पसंद है! डब्ल्यूटीएफ जावास्क्रिप्ट ?! – Prestaul

+0

तो मुझे लगता है कि मेरे समापन प्रश्न का उत्तर, यह तब है जब यह 'बूलियन' है। – Domenic

उत्तर

6

ऐसा लगता है कि जब एक आदिम बूलियन call या apply करने के लिए पहले तर्क के रूप में पारित हो जाता है, यह स्वत: बॉक्सिंग एक Boolean वस्तु में है। यह फ़ायरफ़ॉक्स 4 पर Firebug में स्पष्ट है:

>>> (function() { return this; }).call(false) 
Boolean {} 

Chrome की निरीक्षक में, यह शुरू में भ्रामक है लेकिन एक छोटे से जांच सच्चाई का पता चलता है:

>>> (function() { return this; }).call(false) 
false 
>>> typeof (function() { return this; }).call(false) 
"object" 

सभी जावास्क्रिप्ट वस्तुओं रहे हैं "truthy", यहां तक ​​कि new Boolean(false) और new Number(0)। इसलिए, दो निषेध ऑपरेटरों (!! चाल) का उपयोग करके उन्हें true बूलियन तक पहुंचाता है।

4

मुझे इस पंक्ति को उस विनिर्देशन में मिला जो व्यवहार को बताता है।

 
3. Else if Type(thisArg) is not Object, set the 
    ThisBinding to ToObject(thisArg). 

मूलतः false मूल्य एक बूलियन वस्तु में परिवर्तित हो जाएगा। ! ऑपरेटर का पहला एप्लिकेशन ऑब्जेक्ट को true में परिवर्तित कर देगा और फिर false पर उलटा होगा। ! ऑपरेटर का दूसरा एप्लिकेशन false से true में उलटा होगा।

पूर्ण पाठ

 
10.4.3 Entering Function Code 

The following steps are performed when control enters the 
execution context for function code contained in function 
object F, a caller provided thisArg, and a caller provided argumentsList: 

1. If the function code is strict code, set the ThisBinding to thisArg. 
2. Else if thisArg is null or undefined, 
    set the ThisBinding to the global object. 
3. Else if Type(thisArg) is not Object, set the 
    ThisBinding to ToObject(thisArg). 
4. Else set the ThisBinding to thisArg. 
5. Let localEnv be the result of calling NewDeclarativeEnvironment 
    passing the value of the [[Scope]] internal 
    property of F as the argument. 
6. Set the LexicalEnvironment to localEnv. 
7. Set the VariableEnvironment to localEnv. 
8. Let code be the value of F‘s [[Code]] internal property. 
9. Perform Declaration Binding Instantiation using the function code 
    code and argumentsList as described in 
+0

ओहोह मैं वास्तव में स्वीकार्य उत्तर के रूप में जाने के लिए प्रेरित हूं क्योंकि यह कल्पना का संदर्भ देता है ... लेकिन विचार का उत्तर पालन करना बहुत आसान था, इसलिए मैं इसे किसी और के लिए शीर्ष पर रखना चाहता हूं :)। – Domenic

+0

@Domenic - समझने योग्य, अगर वे थोड़ा गहरा खोदना चाहते हैं तो उन्हें बस थोड़ा सा स्क्रॉल करना होगा। – ChaosPandion

संबंधित मुद्दे