簡體   English   中英

模塊中class_eval和instance_eval的區別

[英]Difference between class_eval and instance_eval in a module

代碼:

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

Output 是:

test1
test2

我意識到一個在 class 的上下文中進行評估,而另一個在實例的上下文中進行評估,但是......在這種情況下,他們為什么會這樣返回? (我本以為其中一個會出現異常。)

在您的示例中沒有區別。

> Foo1.instance_eval { puts self } 
Foo1

> Foo1.class_eval { puts self }
Foo1

class 的實例是 class 本身。 instance_eval在這里沒有給你任何“額外”的東西。 但是,如果您在 class 的實例上使用它,那么您會得到不同的行為。 Foo1.new.instance_eval...

看到這里有一個很好的解釋:
如何理解 class_eval() 和 instance_eval() 的區別?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM