एक नौसिखिया प्रश्न, नए और प्रारंभिक के बीच क्या अंतर है?स्मॉलटॉक में नए और प्रारंभ करने के बीच अंतर?
ऑस्कर
एक नौसिखिया प्रश्न, नए और प्रारंभिक के बीच क्या अंतर है?स्मॉलटॉक में नए और प्रारंभ करने के बीच अंतर?
ऑस्कर
बिल्कुल। जब आप संदेश # नया भेजते हैं, तो यह न केवल ऑब्जेक्ट बनाता है, बल्कि मैसेज # प्रारंभिक भेजता है। यह आपको वस्तुओं के प्रारंभिकरण को अनुकूलित करने देता है। देखो:
Behavior >> new
"Answer a new initialized instance of the receiver (which is a class) with no indexable variables. Fail if the class is indexable."
^ self basicNew initialize
और फिर:
ProtoObject >> initialize
"Subclasses should redefine this method to perform initializations on instance creation"
और:
Behaviour >> basicNew
"Primitive. Answer an instance of the receiver (which is a class) with no
indexable variables. Fail if the class is indexable. Essential. See Object
documentation whatIsAPrimitive."
<primitive: 70>
self isVariable ifTrue: [^self basicNew: 0 ].
"space must be low"
OutOfMemory signal.
^ self basicNew "retry if user proceeds"
तो ... # basicNew उस वस्तु बनाता आदिम है। आम तौर पर, आप # नया उपयोग करते हैं और यदि आप विशेष रूप से कुछ भी नहीं चाहते हैं, तो आप # प्रारंभ नहीं कर सकते हैं और इसलिए #ProtoObject का खाली कार्यान्वयन निष्पादित किया जाएगा। अन्यथा, आप सीधे #basicNew भेज सकते हैं लेकिन आपको शायद यह नहीं करना चाहिए।
चीयर्स
।
Bavarious सही है।
Behavior >> new
"Answer a new instance of the receiver. If the instance can have indexable variables, it will have 0 indexable variables."
"Primitive fails if the class is indexable."
<primitive: 70>
self isVariable ifTrue: [^self new: 0].
self primitiveFailed
Object >> initialize
"Initialize the object to its default state. This is typically used in a convention that the class implements the #new method to call #initialize automatically. This is not done for all objects in VisualWorks, but the initialize method is provided here so that subclasses can call 'super initialize' and not get an exception."
^self.
यह ऑब्जेक्टिव-सी के आवंटन-इनिट पैटर्न से भी मेल खाता है: 'myObj: = [[NSObject alloc] init] '। बहुत आश्चर्यजनक नहीं है, कि :) –
हालांकि कुछ बोलीभाषाएं 'नए' पर 'प्रारंभिक' भेजती हैं, यह स्मॉलटॉक -80 के लिए सच नहीं है। –
मेरा मानना है कि मैंने ऐसे उदाहरण देखे हैं जहां लोग माइक्लास श्रेणी में शुरुआती कोड डालते हैं >> MyClass के बजाय नया >> प्रारंभ करें, आप ऐसा क्यों करेंगे यदि वे मूल रूप से एक ही समय में आते हैं? – oscarkuo
@oykuo - >> प्रारंभिक वस्तु द्वारा उत्तर दिया गया ऑब्जेक्ट भेजा गया है (ऑब्जेक्ट संदेश नहीं है >> नया भेजा गया था)। >> प्रारंभिक रूप से instVars तक पहुंच है जो शायद पहले मौजूद नहीं था >> नया भेजा गया था। (हो सकता है कि आप क्लास साइड प्रारंभिकरण के बारे में सोच रहे हों?) – igouy