We can do away with the anonymous function wrapper by using Function.bind
, which was introduced in ECMAScript 5. This works in the latest versions of browsers, and you can patch older browsers by defining the function yourself. An example definition is given at the Mozilla Developer Network.
Here's an example of how bind
can be used with Jasmine.
describe('using bind with jasmine', function() {
var f = function(x) {
if(x === 2) {
throw new Error();
}
}
it('lets us avoid using an anonymous function', function() {
expect(f.bind(null, 2)).toThrow();
});
});
The first argument provided to bind
is used as the this
variable when f
is called. Any additional arguments are passed to f
when it is invoked. Here 2
is being passed as its first and only argument.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…