Skip to content
jshacks.dev
Functions

Turn any method into a standalone function with call.bind

Turn any method into a standalone function with call.bind in JavaScript, for example hasOwnProperty or slice, so you can pass it to map or filter.

1 min read
Summarize in AI

A method needs its this. Function.prototype.call.bind(method) makes a function that takes the this value as its first argument, so it can be passed around as a plain function.

JavaScript
const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
const trim = Function.prototype.call.bind(String.prototype.trim);

console.log(hasOwn({ a: 1 }, 'a'));
console.log(hasOwn({ a: 1 }, 'b'));
console.log(['  one ', ' two'].map(trim));
Text
true
false
[ 'one', 'two' ]

call.bind(trim) produces a function equivalent to (thisArg, ...args) => trim.call(thisArg, ...args). When map calls it with each string, that string becomes this inside trim. This gives the "uncurried this" style, and is described under call.

It is a curiosity in modern code. Object.hasOwn replaces the first line and an arrow function is easier to read than the second. One catch with map: it also passes the index and the array, so trim ignores them but a method with optional arguments would not.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read
Functions

Use a generator to paginate any API

Use a generator to paginate any API in JavaScript, hiding the page loop behind for await so callers see one stream of items. Works in Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.