【发布时间】:2011-04-17 09:58:16
【问题描述】:
一个新手问题,new和initialize有什么区别?
【问题讨论】:
标签: smalltalk
一个新手问题,new和initialize有什么区别?
【问题讨论】:
标签: smalltalk
没错。当您发送消息#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,但您可能不应该这样做。
干杯
【讨论】:
new 上发送initialize,但Smalltalk-80 并非如此。
使用new创建一个新对象,而initialize方法在新对象创建时执行,并初始化对象。
【讨论】:
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]。这并不奇怪,:)