Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.
bind, call, and apply fix this when the call site is wrong
When a function is passed around, implicit this is lost. JavaScript gives you tools to set this explicitly — similar in spirit to carrying $this into a closure in PHP.
PHP habit: binding context manually
<?php
class Logger {
public function write(string $msg): void {
echo "[{$this->name}] $msg\n";
}
}
$logger = new class {
public string $name = 'app';
public function run(Logger $log): void {
$bound = \Closure::bind(
fn (string $m) => $log->write($m),
$log,
Logger::class
);
$bound('saved');
}
};
You rarely write this in PHP because method calls keep $this. In JavaScript you see bind often.
JavaScript equivalent
const logger = {
name: 'app',
write(msg) {
console.log(`[${this.name}] ${msg}`);
},
};
const write = logger.write;
// call — invoke now with chosen this
write.call(logger, 'saved');
// apply — same, arguments as array
write.apply(logger, ['via apply']);
// bind — return a new function with fixed this
const bound = logger.write.bind(logger);
bound('saved later');
| API | Invokes now? | Arguments |
|---|---|---|
fn.call(thisArg, a, b) |
Yes | Comma-separated |
fn.apply(thisArg, [a, b]) |
Yes | Array |
fn.bind(thisArg) |
No — returns new function | Set when you call the result |
Partial application with bind
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2);
console.log(double(5)); // 10
null as this when the function does not use this.
Try it
Use the amber Try it panel below. Click Run.
const api = {
base: 'https://api.example',
path(resource) {
return `${this.base}/${resource}`;
},
};
const broken = api.path;
console.log('call fixes it', api.path.call(api, 'orders'));
const boundPath = api.path.bind(api);
console.log('bind fixes it', boundPath('users'));
Both call and bind attach this to api when path was detached.
From PHP to JavaScript — Control Flow, Functions, and Scope