class MyClass
def MyFun
puts self
end
end
mine = MyClass.new
mine.MyFun # => #<MyClass:0x10a3ee670>
由于模块、类、def 都改变了范围,这里 self 应该是 MyFun 而不是 MyClass,因为它在 def...end 中。为什么它仍然保留在 MyClass 中?
class MyClass
def MyFun
puts self
end
end
mine = MyClass.new
mine.MyFun # => #<MyClass:0x10a3ee670>
由于模块、类、def 都改变了范围,这里 self 应该是 MyFun 而不是 MyClass,因为它在 def...end 中。为什么它仍然保留在 MyClass 中?
self
是当前上下文对象。MyFun
不是一个对象,而是一个方法——具体来说,它是 MyClass 的一个实例方法。所以在里面MyFun
,self
将是正在执行的 MyClass 的实例MyFun
。
范围self
:
在类定义中,
self
总是它class constants(instance of Class)
本身。(实例方法除外)。在实例方法内部,
self
是该类常量的实例,它刚刚调用了相应的方法。
p RUBY_VERSION
class Foo
def self.talk
p "here SELF is-> #{self}"
end
def display
p "here SELF is-> #{self}"
end
p "here SELF is-> #{self}"
end
Foo.talk
foo = Foo.new
foo.display
class << foo
p "here SELF is-> #{self}"
end
输出:
"2.0.0"
"here SELF is-> Foo"
"here SELF is-> Foo"
"here SELF is-> #<Foo:0x1fc7fa0>"
"here SELF is-> #<Class:#<Foo:0x1fc7fa0>>"
在您的示例MyFun
中是一个实例方法,self
实际上也是一个MyClass
.
返回的东西 mine.MyFun
实际上是实例文字。如果它是一个类文字,那将是 jsut plainly MyClass
。自己测试一下
class Example
def asdf
self
end
end
Example.new.asdf.class #=> Example