Closure Binding
Who owns the call's context — Closure::bind against rebinding this/the receiver across 10 languages.
C C23
#include <stdio.h>
/* C closures don't exist: a "bound callable" is a function pointer plus a
void* context carried by hand — every callback ABI has this shape */
typedef struct {
const char *greeting;
} Greeter;
static void call_with(void (*fn)(void *), void *ctx) {
fn(ctx); /* the context plays the role of `this` */
}
static void greet(void *ctx) {
Greeter *g = ctx;
printf("%s\n", g->greeting);
}
int main(void) {
Greeter g = { "bound hello" };
call_with(greet, &g); /* greet bound to g */
return 0;
}
bound hello
C++ C++26
#include <cstdio>
#include <string>
#include <functional>
class Vault {
public:
std::string secret = "treasure";
std::string read() const { return secret; }
};
int main() {
Vault v;
// capturing by reference embeds the object into the callable itself
auto peek = [&v] { return "peek: " + v.read(); };
std::printf("%s\n", peek().c_str());
// std::bind bakes the target object into a call wrapper
auto bound = std::bind(&Vault::read, &v);
std::printf("%s\n", bound().c_str());
return 0;
}
peek: treasure treasure
C# v11.0.100
using System;
using System.Reflection;
var v = new Vault();
Console.WriteLine(v.Thief()());
// CreateDelegate binds a method onto an explicit target
var open = (Func<Vault, string>)Delegate.CreateDelegate(
typeof(Func<Vault, string>), null, typeof(Vault).GetMethod("Read")!);
Console.WriteLine(open(v));
class Vault
{
private string secret = "treasure";
public string Read() => secret;
public Func<string> Thief() => () => secret; // capture bakes in `this`
}
treasure treasure
Go v1.27.4
package main
import "fmt"
type Counter struct{ n int }
func (c *Counter) Next() int {
c.n++
return c.n
}
func main() {
c := &Counter{n: 0}
bound := c.Next // method value: the receiver is baked in
fmt.Println(bound())
fmt.Println(bound())
unbound := (*Counter).Next // method expression: receiver becomes arg 0
other := &Counter{n: 10}
fmt.Println(unbound(other))
}
1 2 11
Java v27.0.1
import java.util.function.Supplier;
public class Main {
static class Box {
String label;
Box(String label) { this.label = label; }
String read() { return label; }
}
public static void main(String[] args) {
Box b = new Box("bound");
// an instance method reference captures the receiver for good
Supplier<String> bound = b::read;
System.out.println(bound.get());
Supplier<String> other = new Box("fresh")::read;
System.out.println(other.get());
}
}
bound fresh
JavaScript v26.13.1
// bind re-targets `this` and optionally pre-applies arguments
class Vault {
constructor(secret) { this.secret = secret; }
}
const read = function (prefix) { return prefix + this.secret; };
const bound = read.bind(new Vault("treasure"), "bind reads: ");
console.log(bound());
// call/apply bind for one invocation only
console.log(read.call(new Vault("peek"), "call reads: "));
bind reads: treasure call reads: peek
PHP v8.6.0
class Vault {
private string $secret = "treasure";
public function thief(): Closure {
// scope at creation: this closure sees Vault's privates
return function (): string {
return $this->secret;
};
}
}
$v = new Vault();
echo $v->thief()(), "\n";
// bindTo: re-target $this AND widen the class scope
$probe = function (): string {
return "bindTo reads: " . $this->secret;
};
echo $probe->bindTo(new Vault(), Vault::class)(), "\n";
// Closure::bind: the static twin
$peek = Closure::bind(function (): string {
return "bind reads: " . $this->secret;
}, new Vault(), Vault::class);
echo $peek(), "\n";
// without the scope argument the closure keeps global scope: privates hidden
try {
Closure::bind(function (): string {
return $this->secret;
}, new Vault())();
} catch (Error $e) {
echo "Error: ", $e->getMessage(), "\n";
}
treasure bindTo reads: treasure bind reads: treasure Error: Cannot access private property Vault::$secret
Python v3.15.2
import types
class Vault:
def __init__(self):
self.secret = "treasure"
def peek(self):
return "peek: " + self.secret
v = Vault()
bound = types.MethodType(peek, v) # bind the function to the instance
print(bound())
v.expose = bound # attach as an instance attribute
print(v.expose())
peek: treasure peek: treasure
Rust v1.99.1
struct Vault {
secret: String,
}
fn main() {
let v = Vault { secret: "treasure".to_string() };
// captures are decided at definition: borrow or move, by usage
let peek = |w: &Vault| format!("peek: {}", w.secret);
let by_move = move || v.secret.clone(); // takes ownership of v
println!("{}", peek(&Vault { secret: "second".to_string() }));
println!("{}", by_move());
// after the move, v is gone: binding is lexical, not runtime retargeting
}
peek: second treasure
TypeScript v26.13.1
// TS types `this` so bind targets are checked at compile time
interface Vault { secret: string; }
const read = function (this: Vault, prefix: string): string {
return prefix + this.secret;
};
const bound = read.bind({ secret: "treasure" }, "bind reads: ");
console.log(bound());
console.log(read.call({ secret: "peek" }, "call reads: "));
bind reads: treasure call reads: peek
Language differences
C: no closures (example): binding means a function pointer plus a hand-carried void* context — the shape underlying every callback ABI; what is bound and when it dies is entirely the programmer's job.
C++: capture is binding (example): a lambda capturing by reference embeds the object into the callable; std::bind bakes a member function and its target into a call wrapper; binding happens at construction with no runtime redirection.
C#: delegates carry their target by birth (example): lambda captures bake this into the delegate, and Delegate.CreateDelegate can bind explicitly or build an open delegate — one dimension fewer than PHP, since private access is settled by compile-time visibility.
Go: method values versus method expressions (example): c.Next is a method value with the receiver baked in, while (*Counter).Next lifts the receiver to the first argument — both binding shapes are decided at compile time.
Java: method references capture the receiver (example): b::read captures b once and for all; there is no general rebind — same for lambda captures, fixed at creation.
JavaScript: Function.prototype.bind (example): bind re-targets this permanently and can pre-apply arguments, while call/apply bind for a single invocation — JS is the poster child of runtime this control; arrow functions are the exception (captured at definition, bind-proof).
PHP: Closure::bind/bindTo (example): the two parameters re-target $this and the class scope (which governs private/protected visibility) at once — one dimension beyond JS bind; without a scope argument the closure keeps its original scope and privates stay hidden; binding an instance to a static closure is deprecated since 8.5; Closure::fromCallable and the first-class callable syntax lock the scope at creation.
Python: types.MethodType (example): wrapping a function into a bound method (a half match) — once bound it can even be attached as an instance attribute; there is no symmetric unbind/rebind primitive and changing self at runtime means re-wrapping.
Rust: a fundamentally different capture model (example): the closure decides borrow or move at its definition site, binding is lexical; there is no this at all, so re-binding has no foothold — ownership and borrow checking replace runtime context management.
TypeScript: the typed this parameter (example): function (this: Vault) annotates this so bind/call targets are validated at compile time; at runtime it is the same JS bind/call machinery.