本文介绍了是“自我扩展"吗?与"module_function"相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
extend self
和module_function
是制作它的两种方法,因此您可以调用模块上的方法,如果包含该模块,也可以调用它.
extend self
and module_function
are two ruby ways to make it so you can call a method on a module and also call it if you include that module.
这些方式的最终结果之间有什么区别吗?
Are there any differences between the end results of those ways?
推荐答案
module_function
将给定的实例方法设为私有,然后进行复制并将其作为公共方法放入模块的元类中. extend self
将所有实例方法添加到模块的单例中,而使其可见性保持不变.
module_function
makes the given instance methods private, then duplicates and puts them into the module's metaclass as public methods. extend self
adds all instance methods to the module's singleton, leaving their visibilities unchanged.
module M
extend self
def a; end
private
def b; end
end
module N
def c; end
private
def d; end
module_function :c, :d
end
class O
include M
include N
end
M.a
M.b # NoMethodError: private method `b' called for M:Module
N.c
N.d
O.new.a
O.new.b # NoMethodError: private method `b' called for O
O.new.c # NoMethodError: private method `c' called for O
O.new.d # NoMethodError: private method `d' called for O
这篇关于是“自我扩展"吗?与"module_function"相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!