Io语言中newSlot和setSlot有什么区别?

发布于 2024-11-06 19:48:31 字数 121 浏览 4 评论 0原文

在Io语言中,有2种创建槽的方法:newSlot和setSlot。两者似乎都有相似的行为,除了 newSlot 还创建了一个 setter 之外。在什么情况下需要在创建槽的同时创建setter? setter 的具体目的是什么?

In the Io Language, there are 2 methods for creating slots: newSlot and setSlot. Both seem to have similar behavior except newSlot also creates a setter. What cases are there for a needing a setter to be created at the same time as slot creation? What exactly is the purpose of the setter anyway?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴梦长久 2024-11-13 19:48:31

我相信它提供了良好的编码实践的便利。因此,如果您想公开对象属性,那么 newSlot 或其同义词 ::= 是首选方法。

newSlot 可以让事情看起来更好。例如。

Animal := Object clone do (
    legs ::= nil    // creates leg slot  & setLegs() setter
    tail ::= nil    // creates tail slot & setTail() setter
)

// I think below is more aesthetic 
Cat := Animal clone setLegs(4) setTail(1)

// compared to this
Dog := Animal clone do (legs = 4; tail = 1)

而且它还可以绕过 do() 上下文。例如。

Pet := Animal clone do (
    name ::= nil
)

myPetCats := list("Ambrose", "Fluffy", "Whiskers") map (petName,
    Pet clone do (name = petName)   // throws exception
)

Pet 克隆 do (name = petName) 将抛出 Exception: Pet does not respond to 'petName' 因为 do() 在克隆的 Pet 上下文,因此它看不到 petName

因此,您需要使用设置器:

myPetCats := list("Ambrose", "Fluffy", "Whiskers") map (petName,
    Pet clone setName(petName)
)

I believe its a convenience which provides good coding practises. Thus if you want to expose an objects attribute then newSlot or its synonym ::= are the preferred way to go.

newSlot can make things look nicer. For eg.

Animal := Object clone do (
    legs ::= nil    // creates leg slot  & setLegs() setter
    tail ::= nil    // creates tail slot & setTail() setter
)

// I think below is more aesthetic 
Cat := Animal clone setLegs(4) setTail(1)

// compared to this
Dog := Animal clone do (legs = 4; tail = 1)

And also it can get around do() context. For eg.

Pet := Animal clone do (
    name ::= nil
)

myPetCats := list("Ambrose", "Fluffy", "Whiskers") map (petName,
    Pet clone do (name = petName)   // throws exception
)

The Pet clone do (name = petName) will die throwing Exception: Pet does not respond to 'petName' because do() is interpreted within the cloned Pet context and so it cannot see petName.

So instead you need to use the setter:

myPetCats := list("Ambrose", "Fluffy", "Whiskers") map (petName,
    Pet clone setName(petName)
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文