调用super()会导致父类中的其他方法被使用吗?

我有一个关于super的问题我想要确认。 请考虑以下代码示例:

 class InFasionHello def hello person greet person.name end def greet name p 'Dude, hey ' + name end end class OldFasionedHello < InFasionHello def hello person greet person.name if person.old_fashioned super(person) if !person.old_fashioned end def greet name p 'Good Day to you ' + name + '!' end end 

我的问题是,如果我使用的是OldFasionedHello ,那么infasionHello使用本地greet自己还是来自通过super调用它的类?

布丁的证据就在吃。

 class Parent def foo; p self; bar; end # This calls bar on the current object def bar; puts "parent bar"; end end class Child < Parent def foo; super; end # Removing this line changes nothing def bar; puts "child bar"; end end Child.new.foo #=> # #=> child bar # NOTE! Not "parent bar" 

如上所述,召唤super并不会改变自我。 因此,您调用self(显式或隐式,不提供接收器)的方法仍然对原始实例起作用,并将其用于方法查找 。


调用super()相当于调用:

 self.class.superclass.instance_method(__method__).bind(self).call 

…这有助于说明您正在调用方法的实现,就像它在当前实例上一样。 另请注意, supersuper() ,因为前者会神奇地传递提供给当前方法的任何参数。

给定方法内的所有方法调用都是针对self执行的。 实例方法中的self是一个实例本身,并且它是一个实例,它是该方法的接收者。 因此,它启动给定对象的标准方法查找,因此它将始终执行具有给定名称的最顶层方法。

一个极好的例子是class方法:

 class A def foo self.class end end class B < A end B.new.foo #=> B even though foo comes from A