def `self.function` 名称是什么意思? [英] What does def `self.function` name mean?

查看:46
本文介绍了def `self.function` 名称是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释在方法定义中添加 self 的含义是什么?是不是类似于java中的this关键字?

Can anyone explain to me what the meaning of adding self to the method definition is? Is it similar to the this keyword in java?

推荐答案

与其他语言相反,Ruby 没有类方法,但它有附加到特定对象的单例方法.

Contrary to other languages, Ruby has no class methods, but it has singleton methods attached to a particular object.

cat = String.new("cat")
def cat.speak
    'miaow'
end
cat.speak #=> "miaow" 
cat.singleton_methods #=> ["speak"] 

def cat.speak 创建一个附加到对象 cat 的单例方法.

def cat.speak creates a singleton method attached to the object cat.

当你写class A时,相当于A = Class.new :

A = Class.new
def A.speak
    "I'm class A"
end
A.speak #=> "I'm class A" 
A.singleton_methods #=> ["speak"] 

def A.speak 创建一个附加到对象 A 的单例方法.我们称它为类 A 的类方法.

def A.speak creates a singleton method attached to the object A. We call it a class method of class A.

写作时

class A
    def self.c_method
        'in A#c_method'
    end
end

你创建了一个 Class(*) 的实例.在类定义中,Ruby 将 self 设置为 Class 的这个新实例,该实例已分配给常量 A.因此 def self.c_method 等效于 def cat.speak,也就是说你定义了一个附加到对象self的单例方法,当前是类A.

you create an instance of Class(*). Inside the class definition, Ruby sets self to this new instance of Class, which has been assigned to the constant A. Thus def self.c_method is equivalent to def cat.speak, that is to say you define a singleton method attached to the object self, which is currently the class A.

现在类 A 有两个单例方法,我们通常称之为类方法.

Now the class A has two singleton methods, that we commonly call class methods.

A.singleton_methods
 => ["c_method", "speak"] 

(*) 从技术上讲,在这种情况下,A 已经由 A = Class.new 创建,class A重新打开现有的类.这就是为什么我们最后有两个单例方法.但在通常情况下,它是类的第一个定义,它的意思是 Class.new.

(*) technically, in this case where A has already been created by A = Class.new, class A reopens the existing class. That's why we have two singleton methods at the end. But in the usual case where it is the first definition of a class, it means Class.new.

这篇关于def `self.function` 名称是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆