2011-04-17 58 views

回答

7

沒錯。當您發送消息#new時,它不僅創建對象,而且還發送消息#initialize。這可讓您自定義對象的初始化。看:

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是原始的創建對象。通常情況下,你使用#new,如果你不想特殊的東西,你不會實現#initialize,因此#ProtoObject的空實現將被執行。否則,你可以直接發送#basicNew,但你可能不應該這樣做。

乾杯

+2

雖然有些方言在'new'上發送'initialize',但這對Smalltalk-80來說並不正確。 – 2011-04-17 12:03:25

+0

我相信我看過一些例子,人們把初始化代碼放在MyClass類中,而不是MyClass >> initialize,爲什麼你會這樣做,如果它們基本上是在同一時間調用的? – oscarkuo 2011-04-18 01:23:00

+0

@oykuo - >>初始化發送給由>>新的(不是新消息發送到的對象)的對象。 >>初始化可以訪問可能在>> new發送之前不存在的instVars。 (也許你正在考慮類的初始化?) – igouy 2011-04-18 16:13:39

5

有了新創建一個新的對象,而在創建新對象時,執行初始化方法,以及初始化對象。

3

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. 
+0

這也對應於Objective-C的alloc-init模式:'myObj:= [[NSObject alloc] init]'。並不奇怪,那:) – 2011-04-18 08:55:44

相關問題