Last Updated: February 25, 2016
·
2.755K
· markdalgleish

Partial application in JavaScript with 'bind'

The Function prototype's bind method is most commonly used to set the implicit argument of this in a function, e.g.

var myObj = {
    foo: "bar"
};

var getFoo = function() {
    return this.foo;
};

getFoo(); // returns undefined

var boundGetFoo = getFoo.bind(myObj);

boundGetFoo(); // returns "bar"

It can also be used to set a function's explicit arguments, while allowing further arguments to be provided, e.g.

var logHello = console.log.bind(null, "Hello");

logHello("Mark"); // logs ["Hello", "Mark"]

A great example of this is in Node.js, resolving the path to a file from the root of our Node module when inside a subdirectory.

var resolve = require("path").resolve,
    asset = resolve.bind(null, __dirname, "..");

asset("package.json");
// returns "/path/to/modules/package.json"

asset("nested/file.js");
// returns "/path/to/modules/nested/file.js"

Have a fresh tip? Share with Coderwall community!

Post
Post a tip