Smalltalk中new和initialize的区别?

Smalltalk中new和initialize的区别?,smalltalk,Smalltalk,一个新手问题,new和initialize之间有什么区别?使用new创建一个新对象,而initialize方法在创建新对象时执行,并初始化对象。。发送消息“new”时,它不仅创建对象,而且发送消息“initialize”。这使您可以自定义对象的初始化。看: Behavior >> new "Answer a new initialized instance of the receiver (which is a class) with no indexable variables.

一个新手问题,new和initialize之间有什么区别?

使用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" 
以及:

行为>>基本新建
“原语。回答一个不带
可索引变量。如果类是可索引的,则失败。必需。请参阅对象
“文件”是什么意思
self是变量,如果确实:[^self basicNew:0]。
“空间必须很小”
OutOfMemory信号。
^self-basicNew“如果用户继续,请重试”
所以…#basicNew是创建对象的原语。通常,使用#new,如果不需要任何特殊功能,则不实现#initialize,因此将执行#ProtoObject的空实现。否则,您可以直接发送#basicNew,但您可能不应该这样做

干杯是正确的

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个可索引变量
“如果类是可索引的,则基元将失败。”
self是变量ifTrue:[^self new:0]。
自原语
对象>>初始化
“将对象初始化为默认状态。这通常用于类实现自动调用#Initialize的#new method的约定中。这并不是对VisualWorks中的所有对象都这样做,但这里提供了Initialize方法,以便子类可以调用‘super Initialize’而不会得到异常。”
^自我。

虽然有些方言在
新建时发送
初始化
,但Smalltalk-80却不是这样。我相信我见过一些例子,人们将初始化代码放在MyClass>>新建而不是MyClass>>初始化中,如果它们基本上同时被调用,为什么要这样做?@oykuo->initialize被发送到>>new应答的对象(而不是消息>>new被发送到的对象)。>>initialize可以访问在发送>>new之前可能不存在的InstVar。(可能您正在考虑类端初始化?)这也对应于Objective-C的alloc init模式:
myObj:=[[NSObject alloc]init]
。这并不奇怪:)
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.