如何使用调用、应用和绑定在Ruby中的对象上强制使用类似于JavaScript的方法
How to force methods on objects in Ruby similar to JavaScript using call, apply and bind
在JavaScript中,您可以使用调用、应用或绑定方法将方法强行插入对象。我很好奇Ruby中是否有类似的东西。
var item = {
color:"green"
};
function getColor(){
return this.color
};
getColor.call(item);
您可以在Ruby中执行几乎相同的操作:
item = {
color: 'green'
}
get_color = ->(arg) {
arg[:color]
}
get_color.call(item) # => "green"
->(foo) { ... }
是lambda { |foo| ... }
的缩写
另一种选择是使用Ruby类系统:
item = Item.new
item.define_singleton_method(:color) do
"something"
end
item.color
=> "something"
您可以将bind
和UnboundMethod
连接到对象,但仅当对象是UnboundMethod
:的owner
的实例时
class Super
def m(arg) "super #@i #{arg}" end
end
class Sub < Super
def m(arg) "sub #@i #{arg}" end
def initialize; @i = 'sub' end
end
class Unrelated
def m(arg) "unrelated #@i #{arg}" end
end
o = Sub.new
um = Super.instance_method(:m)
bm = um.bind(o)
bm.('works')
# => 'super sub works'
um = Unrelated.instance_method(:m)
bm = um.bind(o)
# TypeError: bind argument must be an instance of Unrelated
相关文章:
- 从 javascript 中的对象方法返回一个对象
- 在Javascript中调用对象方法时不是函数类型错误
- Java Script将对象方法映射到数组中的对象
- 将数据从promise then方法传递到对象方法
- 设置显示后Flash对象方法不可用:无
- 通过引用Javascript中的另一个函数来传递对象方法
- Javascript库对象方法声明
- JavaScript对象范围-在对象方法中使用对象变量
- jQuery:如何使用文字对象方法中的方法来获取全局变量
- Javascript 对象方法不更新变量
- setInterval 只在对象方法上运行一次
- 对象方法中函数中的上下文
- 用JavaScript编写对象方法的最佳方式是什么
- 使用回调处理程序调用函数内部的父对象方法
- 从Javascript中的对象方法中访问全局变量
- 将此(对象)传递到一个对象方法嵌套方法中
- 为什么我得到“;不是函数错误”;对于我的对象方法
- 带有回调的Javascript对象方法中的递归
- 更正Node.js异步管道中的对象方法调用
- 如何在对象方法上调用requestAnimFrame