This is just a brief note to point out that, as of the August 29th Firefox nightly (and I think as of the latest beta, but don’t quote me), SpiderMonkey (and Firefox) now implements ES5‘s new Function.prototype.bind
method — native support for creating functions bound to a pre-specified this
value:
var property = 42; var obj = { property: 17, method: function() { return this.property; } }; var bound = obj.method.bind(obj); assertEq(bound(), 17);
…or with pre-specified leading arguments:
function multiply() { var product = 1; for (var i = 0, sz = arguments.length; i < sz; i++) product *= arguments[i]; return product; } var productTimesFive = multiply.bind(null /* this */, 5); assertEq(productTimesFive(4, 3, 2, 1), 120);
…and, in a feature present only in the ES5 bind
implementation (and not in any of the numerous precursors), they even work with new
:
function Vector() { var args = arguments; this.length = arguments.length; this.get = function(i) { return args[i]; }; this.set = function(i, v) { args[i] = v; }; } var PartialVector = Vector.bind(null /* this, ignored with new */, 3, 7); var threeSevenTen = new PartialVector(10); // new Vector(3, 7, 10)
For more information, see the article on Function.prototype.bind
on MDC. For the utmost information, see the ES5 specification for the method.
As always, you can experiment with a version of Firefox with Function.prototype.bind
by downloading a nightly from nightly.mozilla.org. (Don’t forget to use the profile manager if you want to keep the settings you use with your primary Firefox installation pristine.)