http://kkito.cn/index.php/blog/getArticle/82/ruby_binding
之前在看erb如何parse的时候发现使用了binding这个东东,没有怎么在意,后来发现很多地方都用到了这个binding。
仔细查了一下手册
Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained. Binding objects can be created using Kernel#binding , and are made available to the callback of Kernel#set_trace_func
手册上是这么说的,感觉就是context,在context调用,可以得到context的对象,甚至调用context中的方法。相比于java我更倾向于理解成javascript的闭包概念。
通过binding,send,感觉所有的封装都可以忽略了,java开篇所说的语言的安全性在ruby中根本就无从谈起。看来这些脚本语言还是有很大局限性,不过linux下到是很多软件都是python写的(gtk?)
之前在看erb如何parse的时候发现使用了binding这个东东,没有怎么在意,后来发现很多地方都用到了这个binding。
仔细查了一下手册
Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained. Binding objects can be created using Kernel#binding , and are made available to the callback of Kernel#set_trace_func
手册上是这么说的,感觉就是context,在context调用,可以得到context的对象,甚至调用context中的方法。相比于java我更倾向于理解成javascript的闭包概念。
class TestBinding
def initialize
p "this is initialize"
@tt = "test value"
end
def get_binding
binding
end
def get_value
"return a value"
end
private
def get_private_value
"return a private value"
end
end
def my_value
"it is my value"
end
obj = TestBinding.new
p obj.get_binding
#得到binding对象的属性
p eval("@tt" , obj.get_binding)
#调用binding对象的方法
p eval("get_value" , obj.get_binding)
#即使他是private的,还是可以通过send来调用
p eval("send('get_private_value')" , obj.get_binding)
#如果没有binding,可以理解为当前,则在当前context内,所有的对象和方法都可以被调用
p eval("obj")
p eval("my_value")
#eval("")
=begin
Process started >>>
"this is initialize"
#
"test value"
"return a value"
"return a private value"
#
"it is my value"
<<< Process finished.
=end
通过binding,send,感觉所有的封装都可以忽略了,java开篇所说的语言的安全性在ruby中根本就无从谈起。看来这些脚本语言还是有很大局限性,不过linux下到是很多软件都是python写的(gtk?)