【问题标题】:What changes `self` in Ruby? [duplicate]Ruby 中的“self”发生了什么变化? [复制]
【发布时间】:2013-03-25 20:43:33
【问题描述】:

我完全迷失了 self 关键字。当我们进入模块、类、方法、块或其他所有内容时,它会如何变化?谁能给我一个总结?

在这里,我问的是 self 是如何随着执行而改变的,而不是 self 的含义。

【问题讨论】:

  • 我知道 self 是什么,但我想总结一下 self 在进入模块、类、方法、块或其他所有内容时如何变化。
  • 编辑标题以更好地反映问题。

标签: ruby oop self


【解决方案1】:

与 this 可能指代任意数量的事物的 JavaScript 不同,在 Ruby 中 self 总是指代当前方法的执行上下文。

在class 方法中,self 将引用类本身:

class FooClass
  def self.bar
    self # => FooClass
  end
end

在class 实例方法中,self 将引用该实例:

class FooClass
  def bar
    self # => This instance (FooClass#nnnn)
  end
end

在module 方法中,self 可以引用模块:

module FooModule
  def self.bar
    self # => FooModule
  end
end

当一个模块方法通过include混入时,它会引用一个实例:

module FooModule
  def bar
    self # => (Depends on included context)
  end
end

class BarClass
  include FooModule

  def foo
    bar # => This instance (BarClass#nnnn)
  end
end

唯一棘手的部分是模块,它们之所以棘手只是因为其他东西可以包含它们。最好记住它的方法是self,通常指的是点左侧一侧的东西。即my_object.foo 意味着self 在该方法的直接上下文中是my_object。

通过使用instance_eval 和class_eval 类型操作或class << self 声明来操纵eigenclass,可以在块的上下文中重新定义self。 p>

【讨论】:

    【解决方案2】:

    self 始终引用当前对象。

    class A
      p self # => A
    
      def foo
        p self # => instance of A
      end
    end
    
    module M
      p self # => M
    end
    
    A.new.foo
    

    【讨论】:

    • 这只是一个改写,不是解释。
    • 可能添加instance_eval和朋友作为其他方式改变self
    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 2017-11-09
    • 2016-02-11
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多