闭包绑定
调用的上下文归谁管——Closure::bind 与 10 语言「绑定 this/接收者」对照。
C C23
#include <stdio.h>
/* C 不存在闭包:「绑定的可调用」就是函数指针加手工传递的
void* 上下文——所有回调 ABI 都长这个形状 */
typedef struct {
const char *greeting;
} Greeter;
static void call_with(void (*fn)(void *), void *ctx) {
fn(ctx); /* 上下文扮演 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 绑定到 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;
// 按引用捕获把对象嵌进可调用体本身
auto peek = [&v] { return "peek: " + v.read(); };
std::printf("%s\n", peek().c_str());
// std::bind 把目标对象烤进调用包装器
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 把方法显式绑定到目标对象
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; // 捕获把 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 // 方法值:接收者已烤进去
fmt.Println(bound())
fmt.Println(bound())
unbound := (*Counter).Next // 方法表达式:接收者变成第一个参数
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");
// 实例方法引用一次性捕获接收者,终身绑定
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 重定向 this,并可顺便预置参数
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 只为一次调用绑定
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 {
// 创建处的作用域:这个闭包看得见 Vault 的私有成员
return function (): string {
return $this->secret;
};
}
}
$v = new Vault();
echo $v->thief()(), "\n";
// bindTo:重定向 $this,同时拓宽类作用域
$probe = function (): string {
return "bindTo reads: " . $this->secret;
};
echo $probe->bindTo(new Vault(), Vault::class)(), "\n";
// Closure::bind:静态孪生版
$peek = Closure::bind(function (): string {
return "bind reads: " . $this->secret;
}, new Vault(), Vault::class);
echo $peek(), "\n";
// 不传作用域参数时闭包保持全局作用域:私有成员不可见
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) # 把函数绑定到实例上
print(bound())
v.expose = bound # 作为实例属性挂上去
print(v.expose())
peek: treasure peek: treasure
Rust v1.99.1
struct Vault {
secret: String,
}
fn main() {
let v = Vault { secret: "treasure".to_string() };
// 捕获在定义处决定:借用还是移动,由用法说了算
let peek = |w: &Vault| format!("peek: {}", w.secret);
let by_move = move || v.secret.clone(); // 取得 v 的所有权
println!("{}", peek(&Vault { secret: "second".to_string() }));
println!("{}", by_move());
// move 之后 v 已不存在:绑定是词法的,不能运行期重定目标
}
peek: second treasure
TypeScript v26.13.1
// TS 给 this 标注类型,bind 目标因此有编译期检查
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
语言差异说明
C:无闭包(示例):「绑定」= 函数指针 + 手工传递的 void* 上下文,一切回调 ABI 的底层形状;绑定什么、何时失效全由程序员负责。
C++:捕获即绑定(示例):lambda 按引用捕获把对象嵌进可调用体;std::bind 把成员方法与目标对象烤成调用包装器;绑定发生在构造处,无运行期重定向。
C#:委托天生带目标(示例):lambda 捕获把 this 烤进委托;Delegate.CreateDelegate 可显式指定绑定目标或创建开放委托——比 PHP 少一层「作用域」概念,私有成员访问由编译期可见性决定。
Go:方法值 vs 方法表达式(示例):c.Next 是绑定了接收者的方法值,(*Counter).Next 是接收者升为首参的未绑定形式——绑定的两种形态都是编译期决定。
Java:方法引用绑定接收者(示例):b::read 一次性捕获 b;没有通用 rebind 手段——引用创建即定型,与方法引用同源的 lambda 捕获同理。
JavaScript:Function.prototype.bind(示例):bind 永久重定向 this 并可预置参数,call/apply 只绑一次——JS 是「运行期 this 可控」的代表;箭头函数例外(定义处捕获,不可 bind)。
PHP:Closure::bind/bindTo(示例):双参数可同时重定向 $this 与类作用域(决定 private/protected 可见性)——比 JS bind 多一个作用域维度;不传作用域则保持原作用域,私有成员照旧不可见;8.5 起绑定实例到 static 闭包已弃用;Closure::fromCallable/first-class callable 创建时即锁定作用域。
Python:types.MethodType(示例):把函数包装成绑定方法(半边对应)——绑定后可作实例属性挂载;没有对称的「解绑/换绑」原语,运行期换 self 需要重新包装。
Rust:捕获模型根本不同(示例):闭包在定义处决定借用/移动,绑定是词法的;没有 this 概念——重绑定无从谈起,所有权与借用检查取代了运行期上下文管理。
TypeScript:this 参数类型化(示例):function (this: Vault) 给 this 标类型,bind/call 的目标在编译期校验;运行期与 JS 同一套 bind/call 机制。