JavaScript 欢乐时光乐土
// 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
在红宝石中
# 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 中,即使我无法更改上下文,我也会感到 99% 的快乐。我主要需要简单地将参数绑定到方法。
问题
有没有办法将参数绑定到 Ruby 的实例,Method
这样当我在method.call
没有附加参数的情况下调用时,绑定的参数仍会传递给该方法?
目标
这是一个常见的 JavaScript 习惯用法,我认为它在任何语言中都很有用。目标是将方法传递M
给接收者R
,其中 R 不需要(或不具有)在 R 执行该方法时向 M 发送哪些(或多少)参数的内在知识。
一个 JavaScript 演示,说明这可能是如何有用的
/* 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