Skip to content

Instantly share code, notes, and snippets.

@chrisdickinson
Created September 30, 2011 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdickinson/1254873 to your computer and use it in GitHub Desktop.
Save chrisdickinson/1254873 to your computer and use it in GitHub Desktop.
a language feature i sort of think would be cool for JS.

You know what I'd love? If JavaScript had a unary binding operator.

Don't get me wrong, I love that JS has binding at a language level, but some syntactic sugar might not go amiss. Let's take a look:

    var counter = {count:0}

    counter.count = function() {
        return ++this.count
    }

    // here's the way it is today:
    myFakeHttpRequest.on('data', counter.count.bind(counter))

    // here's the way i'd like it to be:
    myFakeHttpRequest.on('data', @counter.count)

    // the two are equivalent!

So, any object lookup prefixed with a @ operator would automatically bind the last property lookup to the previous object in the lookup chain. If there's only one item in the lookup chain, it binds to the current value of this:

    HttpChunker = function() {
        this.data = []
    }

    // append calls are automatically bound to the instance of HttpChunker
    HttpChunker.prototype.start = function(resp) {
        var append = function(data) { this.data.push(data) }
        resp.on('data', @append)
    }

Further, it'd be cool if the @ operator accepted a binary form so that data could be bound to specific arguments. Pass-through args would just be pass:

var strings = ['07', '10', 'ff']

strings.map((pass, 10) @ parseInt)

// instead of:

strings.map(function(x) { return parseInt(x, 10) })

This would create a language level currying ability. I think it'd be pretty awesome, and increase the readability of blorp.bloop.bind(blorp, bleep, bloop, blop) expressions (for reference, it'd now be (bleep, bloop, blop) @ blorp.bloop.)

Thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment