新手问题 这种语法是什么意思?

linjunhalida · September 01, 2014 · Last by huacnlee replied at September 02, 2014 · 2474 hits

请问一下大家,经常看到两个冒号放在前面的语法,这种语法是回到顶部作用域还是什么?为什么要用它而不用别的?

::ActiveRecord::Base.send(:include, ::ActsAsArchive::Base)

就是回到全局命名空间啊..

#1 楼 @saiga 对,为什么要这样用呢?

直接写不可以吗?

还是因为 local 的空间被污染了?有一个其它定义的 include 方法之类?

#4 楼 @linjunhalida 对,就是避免这种情况..Ruby 会就近查找对应的模块,如果继承链上存在这个模块就直接返回不会再向上回溯

module A; end


class B
  module A; end

  def self.pp
    puts A
  end
end

module C
  module A; end
end

class D
  include C

  def self.pp
    puts A
  end
end

class E < D
  def self.pp
    puts A
  end
end

B.pp #=> B::A
D.pp #=> C::A
E.pp #=> C::A

举个例子。

module Demo
  class ApplicationController < ::ApplicationController
  end
  class OoopsController < ::ApplicationController
  end
end

就是预防 local 空间被污染

其实也类似相对路径和绝对路径

避免同名的类名调用时,程序不知道你是在说“A”,还是“当前类下面的 A”

You need to Sign in before reply, if you don't have an account, please Sign up first.