7
A
回答
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,但你可能不应该这样做。
干杯
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
相关问题
- 1. 在smalltalk中新建并初始化 - 如何传递参数来初始化
- 2. Java中静态初始化和动态初始化有什么区别?
- 3. 构造函数声明和初始化的初始化之间的区别
- 4. C++初始化int与double的区别
- 5. 初始化字典和在Swift中声明有什么区别?
- 6. 在.NET中初始化字符串和不初始化字符串之间的区别
- 7. Smalltalk和python之间的区别?
- 8. 加载模块和初始化模块之间的区别?
- 9. 字段定义和初始化之间的区别?
- 10. 信号量与1和0初始化的区别
- 11. 在Java中初始化ASCII和Hex形式的字节有什么区别吗?
- 12. 初始化字符串时'...'和“...”有什么区别?
- 13. 初始化驱动程序时module_init和subsys_initcall有什么区别?
- 14. 直接声明和初始化返回码是否有区别?
- 15. 在C++中初始化Halide缓冲区
- 16. Typescript/Angular 4:注入服务和初始化为新类有什么区别?
- 17. 初始化,初始化与参数和便利初始化
- 18. java中的初始化初始化
- 19. 临界区初始化(C++)
- 20. 结构和类之间的C++区别VS2015中的初始化怎么样
- 21. 默认初始化与默认构建值的初始化初始化
- 22. 的JavaScript模块创建和初始化
- 23. C++中字符串初始化有什么区别?
- 24. 使用ori和addi初始化MIPS中的值有什么区别?
- 25. 初始包含区块和视口之间的区别
- 26. 新的延迟初始化
- 27. 数组初始化的“新”
- 28. 在Rails中初始化“新用户”
- 29. 在新对象中初始化模拟
- 30. 的Java创建初始化
虽然有些方言在'new'上发送'initialize',但这对Smalltalk-80来说并不正确。 – 2011-04-17 12:03:25
我相信我看过一些例子,人们把初始化代码放在MyClass类中,而不是MyClass >> initialize,为什么你会这样做,如果它们基本上是在同一时间调用的? – oscarkuo 2011-04-18 01:23:00
@oykuo - >>初始化发送给由>>新的(不是新消息发送到的对象)的对象。 >>初始化可以访问可能在>> new发送之前不存在的instVars。 (也许你正在考虑类的初始化?) – igouy 2011-04-18 16:13:39