copy from: http://rubylearning.com/satishtalim/ruby_self.html
每当你的程序跑起来的时候,有且只有一个 self
, 它表示当前或者默认的能够访问的对象. 通过下面的描述可以让你看到究竟当前的 self
表示那个对象
.
顶层上下文
当你在进入任何其他上下文之前,你就处在顶层的上下文. 如一个类的定义, 所以所谓的顶层,也就是在类或者模块之外的东西, 看看下面的代码:
x = 1
这个就是你创建了一个顶层的变量.
或者
def m
end
这个就是你创建了一个顶层的方法,或者就是一个 Object
的实例方法. (虽然 self
不是 Object
), 顶层的方法总是私有的, Ruby 给你定义了一个初始化的 self
作为顶层的对象, 如果你直接在顶层输出 self
的话:
puts self
你会看到一个 main
, 一个特殊的定义作为顶层self
指向的对象,也就是说 main
类的对象就是 Object
.
定义在类或者模块中的 self
定义在类或者模块中的 self, 它代表的就是当前类和模块.
class S
puts "just a class"
puts self
module M
puts 'just a module'
puts self
end
puts 'back in outer level of S'
puts self
end
执行上面的代码,输出的是:
just a class
S
just a module
S::M
back in outer level of S
S
定义在实例方法中的self
当方法被调用的时候, 这个时候 self
它代表的就是调用它的那个对象了.
class S
def m
puts 'class s method m'
puts self
end
end
s = S.new
s.m
输出
Class S method m:
# <S:0x2835908>
这个时候的 self
就是代表当前的实例
定义在单例方法或者类方法中的self
单例方法,他是附属于一个特别的对象上的,他只能够被一个对象访问, 当单例方法被调用的时候, self
它就是拥有这个方法,看下面:
obj = Object.new
def obj.show
print 'i am an object'
puts 'here's self inside a singleton method of mine'
puts self
end
obj.show
print 'an inspecting obj from outside'
puts 'to be sure it's the same object'
puts obj
上面的代码输出:
I am an object: here's self inside a singleton method of mine:
# <Object:0x2835688>
And inspecting obj from outside, to be sure it's the same object:
# <Object:0x2835688>
这个时候得到的两个对象是同一个.
类方法也是和方才的单例类似,它不过指向的对象是当前的类对象,看下面代码:
class S
def S.x
puts 'class method of class s'
puts self
end
end
S.x
输出的就是:
Class method of class S
S
在单例方法中的self
就是那些拥有私有方法的对象.
-eof-