singleton class 和 singleton meth

2018-04-12  本文已影响0人  Joke_Ape

ruby 中 singleton class 和 singleton method 分别是什么
Singleton method
A method which belongs to a single object rather than to an entire class and other objects. 一个方法只属于一个对象,而不是整个类和其他实例化对象。

firstObj = ClassMethods.new
secondObj = ClassMethods.new

def firstObj.singletonMethod
  "Hi am a singlton method available only for firstObj"
end

firstObj.singletonMethod # "Hi am a singlton method available only for firstObj"

secondObj.singletonMethod #undefined method `singletonMethod' for #<ClassMethods:0x32754d8> (NoMethodError)

So this “singletonMethod” belongs only to the firstObj object and won’t be available for other objects of this class. 
If you try to make the secondObj.singletonMethod Ruby will inform you that singletonMethod is an undefined method.

所以,singletonMethod 只属于 firstObj,不能被这个类的其他实例化对象所调用。如果你想用 secondObj.singletonMethod 调用这个单例方法,ruby 会告诉你 singletonMethod 没有定义
If you like to find all the singleton methods for a specific object, you can say objectname.singleton_methods In our case
如果你想找到一个特定对象的所有单例方法,你可以用 objectname.singleton_methods 。在我们的例子里面就是:
firstObj.singleton_methods => ["singletonMethod"]
secondObj.singleton_methods => []

To avoid throwing undefined method error when you try to access a singleton method with some other object
避免调用单例方法****抛出方法未定义的异常:

if secondObj.singleton_methods.include?("singletonMethod")
  secondObj.singletonMethod
end


# 或
if secondObj.singleton_methods.include?( :singletonMethod )
  secondObj.singletonMethod
end
上一篇下一篇

猜你喜欢

热点阅读