新手问题,new和initialize有什么区别?
确切地。当您发送消息#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"
And:
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,但您可能不应该这样做。
Cheers
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)