Gelin Luo
Gelin Luo

Reputation: 14373

Javascript "..." arguments

While watching http://www.youtube.com/watch?v=b0EF0VTs9Dc, I found this kind of javascript code

function unit(value) {
    var monad = Object.create(prototype);
    monad.bind = function (func, args) {
        return func.apply(undefined,
                       [value].concat(
                           Array.prototype.slice.apply(args || [])));
    }
    return monad;
}

is rewritten as

function unit(value) {
    var monad = Object.create(prototype);
    monad.bind = function (func, args) {
        return func(value, ...args);
    }
    return monad;
}

However the latter one doesn't running in Chrome and firefox ( I didn't try IE ). Is it something new in Javascript and not supported in current browsers yet?

Upvotes: 0

Views: 109

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

Is it something new in Javascript and not supported in current browsers yet?

Yes, that's part of the next version of the language specification (ECMAScript 6), which is still a draft.

It's only supported by Firefox, and only experimentally, as stated in the link posted by Dan Heberden.

Part of that can be achieved in current JavaScript. For example, to get all extra, unnamed arguments passed to a function:

function f(x) {
    var args = Array.prototype.slice.call(arguments, f.length);
    console.log(args);
}
f(1,2,3); // logs [2, 3]

Or, to pass them along to another function:

function f(someFunc) {
    var args = Array.prototype.slice.call(arguments, f.length);
    someFunc.apply(null, args);
}
f(function(a,b){
    console.log(a, b);
}, 1, 2); // logs 1 2

Upvotes: 1

Related Questions