Ruby ruby 的 extend 方法为什么在类和实例上实现的逻辑不一致
我们先来看下实例对象extend module的情况
module Foo
def bar
"bar in the Module Foo"
end
end
class FooBar
def bar
"bar in the class FooBar"
end
end
f = FooBar.new
f.extend Foo
f.bar
=> "bar in the Module Foo"
接着看下类对象extend module 的情况
module Foo
def bar
"bar in the Module Foo"
end
end
class FooBar
class << self
def bar
"bar in the class FooBar"
end
end
end
FooBar.extend Foo
FooBar.bar
=> "bar in the class FooBar"
再来看下列代码
module Foo
def bar
puts super
"bar in the Module Foo"
end
end
class FooBar
def bar
"bar in the class FooBar"
end
end
f = FooBar.new
f.extend Foo
f.bar
bar in the class FooBar
=> "bar in the Module Foo"
类extend
module Foo
def bar
"bar in the Module Foo"
end
end
class FooBar
class << self
def bar
puts super
"bar in the class FooBar"
end
end
end
FooBar.extend Foo
FooBar.bar
bar in the Module Foo
=> "bar in the class FooBar"
原来 extend在实例对象上时,创建了一个虚拟类,本身的那个类作为了虚拟类的超类,对象指针指向了虚拟类,方法的调用优先级自然比超类的高, 然而 extend用在类对象上时,也创建了一个虚拟类,这个虚拟类就变成了本身这个类的超类。虽然知道它的原理,但不知道它为什么会这样实现,求解?