JavaScript的快乐时光乐趣土地JavaScript的Function.prototype.bind是否有Ruby等价物?
// make a method
var happy = function(a, b, c) {
console.log(a, b, c);
};
// store method to variable
var b = happy;
// bind a context and some arguments
b.bind(happy, 1, 2, 3);
// call the method without additional arguments
b();
输出。好极了!
1 2 3
在Ruby
# make a method
def sad a, b, c
puts a, b, c
end
# store method to variable
b = method(:sad)
# i need some way to bind args now
# (this line is an example of what i need)
b.bind(1, 2, 3)
# call the method without passing additional args
b.call
所需的输出
1, 2, 3
对于它的价值,我知道JavaScript可以改变的第一个参数的结合上下文传递给.bind
。在Ruby中,即使我无法更改上下文,我也会很开心。我主要需要简单地将参数绑定到方法。
问题
是否有参数绑定到一个Ruby Method
的实例,例如,当我打电话method.call
没有额外的参数,被绑定参数是仍然传递给方法的方法吗?
目标
这是一个常见的JavaScript的成语,我认为这将是任何语言有用。目标是将方法M
传递给接收方R
,其中R不需要(或具有)当R执行该方法时要将哪些(或多少)参数发送给M的固有知识。这如何可能是有用的
/* this is our receiver "R" */
var idiot = function(fn) {
console.log("yes, master;", fn());
};
/* here's a couple method "M" examples */
var calculateSomethingDifficult = function(a, b) {
return "the sum is " + (a + b);
};
var applyJam = function() {
return "adding jam to " + this.name;
};
var Item = function Item(name) {
this.name = name;
};
/* here's how we might use it */
idiot(calculateSomethingDifficult.bind(null, 1, 1));
// => yes master; the sum is 2
idiot(applyJam.bind(new Item("toast")));
// => yes master; adding jam to toast
您的问题请问? :) –
我不是一个参考,但我从来没有见过Ruby写的那种方式。我很好奇......这种方法有一个特别的原因吗?你想达到什么目的? – Mohamad
@Mohamad这是一个常见的JavaScript习惯用法。我为这个问题添加了一些信息。 – naomik