加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 模块中class_eval和instance_eval之间的差异

发布时间:2020-12-17 02:29:36 所属栏目:百科 来源:网络整理
导读:码: module Mod1 def self.included(base) base.class_eval do class self attr_accessor :test end @test = 'test1' end endendmodule Mod2 def self.included(base) base.instance_eval do class self attr_accessor :test end @test = 'test2' end enden
码:

module Mod1
  def self.included(base)
    base.class_eval do
      class << self
        attr_accessor :test
      end
      @test = 'test1'
    end
  end
end

module Mod2
  def self.included(base)
    base.instance_eval do
      class << self
        attr_accessor :test
      end
      @test = 'test2'
    end
  end
end

class Foo1
  include Mod1
end

class Foo2
  include Mod2
end

puts Foo1.test
puts Foo2.test

输出是:

test1
test2

我意识到一个在类的上下文中进行求值,而另一个在实例的上下文中进行求值,但是……在这种情况下,为什么它们会这样返回? (我原本预计会有一个例外.)

解决方法

在你的例子中没有区别.

> Foo1.instance_eval { puts self } 
Foo1

> Foo1.class_eval { puts self }
Foo1

类的实例是类本身. instance_eval在这里没有给你任何额外的东西.但是如果你在一个类的实例上使用它,那么你会得到不同的行为.即Foo1.new.instance_eval ….

请看这里有一个很好的解释:
How to understand the difference between class_eval() and instance_eval()?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读