2011-04-17 59 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

相关问题