簡體   English   中英

是否可以在`class_eval`中定義類方法?

[英]Is it possible to define class methods within `class_eval`?

我知道可以使用class_eval定義實例方法。 是否可以在class_eval的上下文中定義類方法?

對的,這是可能的:

class Foo
end

Foo.class_eval do
  def self.bar
    puts "I'm a class method defined using class_eval and self"
  end

  def baz
    puts "I'm an instance method defined using class_eval without self"
  end
end

Foo.bar # => "I'm a class method defined using class_eval and self"

foo = Foo.new
foo.baz # => "I'm an instance method defined using class_eval without self"

據我所知,這是因為在class_evalself是Foo類,而def Foo.bar會創建一個類方法。

Foo.class_eval do
  ...
end

與以下內容相同:

class Foo
  ...
end

我們需要Module#class_eval來操作一個包含類名的變量。 例如,如果:

klass = Foo

你可以寫:

klass.class_eval do
  ...
end

而關鍵字class需要一個常量。

這里class_eval做了兩件事:

  • 它將self改為klassFoo )的值; 然后呢
  • 以與關鍵字class相同的方式“打開” klassFoo )的值。

暫無
暫無

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

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