为什么在 Ruby 方法名称前添加 self?
在查看一些 Ruby 代码时,我注意到在方法名称前面添加了 self.
声明的方法。例如:
def self.someMethod
//...
end
在方法名称前添加 self.
会对方法产生什么影响?
While looking over some Ruby code I noticed methods declared with self.
prepended to the method name. For example:
def self.someMethod
//...
end
What does prepending self.
to the method name change about the method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
def self.something
是一个类方法,调用方式为:def something
是一个实例方法,调用方式为:区别在于,一个是在类本身上调用,另一个是在类本身上调用在类的实例上。
要定义类方法,您还可以使用类名称,但这将使将来的重构变得更加困难,因为类名称可能会更改。
一些示例代码:
def self.something
is a class method, called with:def something
is an instance method, called with:The difference is that one is called on the class itself, the other on an instance of the class.
To define a class method, you can also use the class name, however that will make things more difficult to refactor in the future as the class name may change.
Some sample code:
自我。使其成为类方法,而不是实例方法。这与其他语言中的静态函数类似。
The self. causes it to become a class method, rather than an instance method. This is similar to static functions in other languages.