【发布时间】:2010-11-18 01:56:56
【问题描述】:
【问题讨论】:
标签: ruby
【问题讨论】:
标签: ruby
class B < A
alias :super_a :a
def a
b()
end
def b
super_a()
end
end
【讨论】:
alias 是否可能已重命名为 alias_method?
:super_a 别名为B.a 而是将其别名为A.a?
B.a 尚未定义...如果您将alias 放在def a 下方,情况并非如此
没有很好的方法,但你可以使用A.instance_method(:a).bind(self).call,它会起作用,但很难看。
您甚至可以在 Object 中定义自己的方法,使其像 java 中的 super:
class SuperProxy
def initialize(obj)
@obj = obj
end
def method_missing(meth, *args, &blk)
@obj.class.superclass.instance_method(meth).bind(@obj).call(*args, &blk)
end
end
class Object
private
def sup
SuperProxy.new(self)
end
end
class A
def a
puts "In A#a"
end
end
class B<A
def a
end
def b
sup.a
end
end
B.new.b # Prints in A#a
【讨论】:
如果您不明确需要从 B#b 调用 A#a,而是需要从 B#a 调用 A#a,这实际上就是您通过 B#b 执行的操作(除非您'这个例子还不够完整,无法说明为什么你从 B#b 调用,你可以从 B#a 中调用 super,就像有时在初始化方法中所做的那样。我知道这很明显,我只是想向任何 Ruby 新手澄清在每种情况下您都不必使用别名(特别是有时称为“周围别名”)。
class A
def a
# do stuff for A
end
end
class B < A
def a
# do some stuff specific to B
super
# or use super() if you don't want super to pass on any args that method a might have had
# super/super() can also be called first
# it should be noted that some design patterns call for avoiding this construct
# as it creates a tight coupling between the classes. If you control both
# classes, it's not as big a deal, but if the superclass is outside your control
# it could change, w/o you knowing. This is pretty much composition vs inheritance
end
end
【讨论】: