目录
正在加载目录…
正在阅读专栏 Crafting Interpreters:手写解释器 第 14 篇 · 共 35 篇 · 40%

Classes:对象、方法与 this 绑定

发布于 2026-09-16 19:08 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 4,728 · 预计阅读 10 分钟 👁 20 次阅读

Crafting Interpreters:Classes

本章为 Lox 加入 classes、instances、fields、methods、this,以及构造器和 initializer。

TL;DR

  • Class declaration 创建 class object;instance 保存 fields,class 保存 methods。
  • Property access 先查找 instance field,再查找 class method;set expression 只写入 instance field。
  • method 通过 closure 绑定 this,使同一个 method 在不同 instance 上调用时拥有不同接收者。
  • init() 是特殊 initializer:调用后总是返回新建的 instance,即使函数体中显式 return。
  • Class、instance、method 都实现统一的 callable 语义,constructor call 因而可以复用普通 function-call machinery。

目录

章节内容
OOP and classesobject model
Class declarations声明与 method
Creating instancesclass call 与 instance
Properties on instancesget/set
Methods on classesmethod lookup
Thisreceiver binding
Constructors and initializersinit()
Challenges扩展练习
Design Note:Prototypes and Powerclass 与 prototype

OOP and classes

Object-oriented programming 把 data 与操作 data 的行为组织在一起。Lox 的 class 是一等 runtime value,可以存储在变量中、传给 function,也可以被调用来创建 instance。

circle

Class object 保存 method;instance 保存 fields。调用 class 时创建 instance,调用 instance 上的 method 时再把 instance 作为 this 绑定到 method closure。

Class declarations

class declaration 读取 class name 和一组 method declarations。每个 method 类似 function,但保存为 LoxFunction,并放入 LoxClass 的 method map。class statement 执行时创建 class object,并在当前 environment 定义名称。

method 的语法树与 function body 类似,因此 parser 可以复用 parameters 和 block parsing。区别在于 method 不需要 fun keyword,而且 resolver 要知道当前是在 function 还是 class 中。

Creating instances

LoxClass 实现 LoxCallable。class 的 arity 由 init method 决定;调用 class 时先创建 LoxInstance,再调用 initializer(如果存在),最后返回 instance。

class call 的执行路径可以复用 function call:检查 arity、创建 call environment、绑定 arguments、执行 body。class 只是把 call 的结果改成 instance,并在初始化阶段运行 init。

Properties on instances

instance property access 使用 dot syntax。get expression 首先检查 instance.fields;如果没有该 field,再从 class 查找 method,并返回绑定后的 method。

zip

set expression 要求左侧是 instance。它先求值 object,再求值右侧 value,最后写入 field:

setter

字段 lookup 先于 method lookup,因此 instance field 可以 shadow 同名 method。对非-instance 值读取或写入 property 会产生 runtime error。

Methods on classes

LoxClass 的 findMethod(name) 在 method map 中查找。method 本身是 LoxFunction,返回前需要 bind(instance),把 this 放入一个新的 Environment。

method

同一个 method declaration 可以绑定到多个 instance,每次绑定都产生不同 closure:

closure

This

this 是一个特殊的 variable expression。resolver 在 class scope 中把 this 标记为已定义;解释 class method 时,绑定 Environment 中的 this 让 method body 能访问接收者。

bound method

this 不能在 class 外部使用。nested function 是否能访问 this,取决于它是否通过 closure 捕获了 method 的环境;这也是 lexical scope 和 resolver 协作的地方。

Constructors and initializers

如果 class 有名为 init 的 method,它就是 initializer。class call 创建 instance 后调用 init,并把 instance 作为 this。无论 init 是否显式 return,最终结果都必须是 instance。

call

直接调用 obj.init() 也应返回 obj,而不是显式 return 的值。这样初始化方法的语义始终稳定,不会因为调用方式不同而改变。

Challenges

1. Class fields

允许 class declaration 直接声明默认 field,并决定默认值是在 class 创建时还是 instance 创建时计算。

2. Private properties

设计 private field 或 method。说明 parser、resolver 和 runtime lookup 需要怎样改变,以及继承章节如何处理可见性。

3. Static methods

添加 class-level static method,使 method 可以通过 class object 调用而不需要 instance。

4. Multiple constructors

支持多个构造器或 named constructors,并说明它们与统一的 callable/arity interface 如何协作。

Design Note:Prototypes and Power

Class-based object model 通过 class 描述 instance 的结构与行为;prototype-based model 则让对象直接委托给另一个对象。两者都能表达共享行为、覆盖属性和动态 dispatch。

Class 的优势是关系显式、工具容易展示;prototype 的优势是运行时组合灵活、无需先定义固定 class hierarchy。语言设计不应只追求最强表达能力:更强的动态能力也意味着 lookup、mutation 和错误诊断更难理解。

原文代码片段

本节按官方页面顺序保留本章所有 grammar、Java 和测试代码片段,便于与上文译文逐段对照。

参考资料

Code block 1

text
declaration    → classDecl
               | funDecl
               | varDecl
               | statement ;

classDecl      → "class" IDENTIFIER "{" function* "}" ;

Code block 2

text
function       → IDENTIFIER "(" parameters? ")" block ;
parameters     → IDENTIFIER ( "," IDENTIFIER )* ;

Code block 3

java
class Breakfast {
  cook() {
    print "Eggs a-fryin'!";
  }

  serve(who) {
    print "Enjoy your breakfast, " + who + ".";
  }
}

Code block 4

java
      "Block      : List<Stmt> statements",

Code block 5

java
      "Class      : Token name, List<Stmt.Function> methods",

Code block 6

java
      "Expression : Expr expression",

Code block 7

text
    try {

Code block 8

java
      if (match(CLASS)) return classDeclaration();

Code block 9

java
      if (match(FUN)) return function("function");

Code block 10

java
  private Stmt classDeclaration() {
    Token name = consume(IDENTIFIER, "Expect class name.");
    consume(LEFT_BRACE, "Expect '{' before class body.");

    List<Stmt.Function> methods = new ArrayList<>();
    while (!check(RIGHT_BRACE) && !isAtEnd()) {
      methods.add(function("method"));
    }

    consume(RIGHT_BRACE, "Expect '}' after class body.");

    return new Stmt.Class(name, methods);
  }

Code block 11

java
  @Override
  public Void visitClassStmt(Stmt.Class stmt) {
    declare(stmt.name);
    define(stmt.name);
    return null;
  }

Code block 12

java
  @Override
  public Void visitClassStmt(Stmt.Class stmt) {
    environment.define(stmt.name.lexeme, null);
    LoxClass klass = new LoxClass(stmt.name.lexeme);
    environment.assign(stmt.name, klass);
    return null;
  }

Code block 13

java
package com.craftinginterpreters.lox;

import java.util.List;
import java.util.Map;

class LoxClass {
  final String name;

  LoxClass(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return name;
  }
}

Code block 14

java
class DevonshireCream {
  serveOn() {
    return "Scones";
  }
}

print DevonshireCream; // Prints "DevonshireCream".

Code block 15

java
class Bagel {}
Bagel();

Code block 16

java
import java.util.Map;

Code block 17

java
class LoxClass implements LoxCallable {

Code block 18

text
  final String name;

Code block 19

java
  @Override
  public Object call(Interpreter interpreter,
                     List<Object> arguments) {
    LoxInstance instance = new LoxInstance(this);
    return instance;
  }

  @Override
  public int arity() {
    return 0;
  }

Code block 20

java
package com.craftinginterpreters.lox;

import java.util.HashMap;
import java.util.Map;

class LoxInstance {
  private LoxClass klass;

  LoxInstance(LoxClass klass) {
    this.klass = klass;
  }

  @Override
  public String toString() {
    return klass.name + " instance";
  }
}

Code block 21

java
class Bagel {}
var bagel = Bagel();
print bagel; // Prints "Bagel instance".

Code block 22

text
someObject.someProperty

Code block 23

text
call           → primary ( "(" arguments? ")" | "." IDENTIFIER )* ;

Code block 24

java
      "Call     : Expr callee, Token paren, List<Expr> arguments",

Code block 25

java
      "Get      : Expr object, Token name",

Code block 26

java
      "Grouping : Expr expression",

Code block 27

java
    while (true) { 
      if (match(LEFT_PAREN)) {
        expr = finishCall(expr);

Code block 28

java
      } else if (match(DOT)) {
        Token name = consume(IDENTIFIER,
            "Expect property name after '.'.");
        expr = new Expr.Get(expr, name);

Code block 29

text
      } else {
        break;
      }
    }

Code block 30

java
  @Override
  public Void visitGetExpr(Expr.Get expr) {
    resolve(expr.object);
    return null;
  }

Code block 31

java
  @Override
  public Object visitGetExpr(Expr.Get expr) {
    Object object = evaluate(expr.object);
    if (object instanceof LoxInstance) {
      return ((LoxInstance) object).get(expr.name);
    }

    throw new RuntimeError(expr.name,
        "Only instances have properties.");
  }

Code block 32

java
  private LoxClass klass;

Code block 33

java
  private final Map<String, Object> fields = new HashMap<>();

Code block 34

java
  LoxInstance(LoxClass klass) {

Code block 35

java
  Object get(Token name) {
    if (fields.containsKey(name.lexeme)) {
      return fields.get(name.lexeme);
    }

    throw new RuntimeError(name, 
        "Undefined property '" + name.lexeme + "'.");
  }

Code block 36

text
someObject.someProperty = value;

Code block 37

text
assignment     → ( call "." )? IDENTIFIER "=" assignment
               | logic_or ;

Code block 38

java
      "Logical  : Expr left, Token operator, Expr right",

Code block 39

java
      "Set      : Expr object, Token name, Expr value",

Code block 40

java
      "Unary    : Token operator, Expr right",

Code block 41

java
        return new Expr.Assign(name, value);

Code block 42

java
      } else if (expr instanceof Expr.Get) {
        Expr.Get get = (Expr.Get)expr;
        return new Expr.Set(get.object, get.name, value);

Code block 43

text
      }

Code block 44

java
  @Override
  public Void visitSetExpr(Expr.Set expr) {
    resolve(expr.value);
    resolve(expr.object);
    return null;
  }

Code block 45

java
  @Override
  public Object visitSetExpr(Expr.Set expr) {
    Object object = evaluate(expr.object);

    if (!(object instanceof LoxInstance)) { 
      throw new RuntimeError(expr.name,
                             "Only instances have fields.");
    }

    Object value = evaluate(expr.value);
    ((LoxInstance)object).set(expr.name, value);
    return value;
  }

Code block 46

java
  void set(Token name, Object value) {
    fields.put(name.lexeme, value);
  }

Code block 47

text
var m = object.method;
m(argument);

Code block 48

java
class Box {}

fun notMethod(argument) {
  print "called function with " + argument;
}

var box = Box();
box.function = notMethod;
box.function("argument");

Code block 49

text
breakfast(omelette.filledWith(cheese), sausage);

Code block 50

text
var eggs = omelette.filledWith(cheese);
breakfast(eggs, sausage);

Code block 51

text
fun callback(a, b, c) {
  object.method(a, b, c);
}

takeCallback(callback);

Code block 52

text
takeCallback(object.method);

Code block 53

java
class Person {
  sayName() {
    print this.name;
  }
}

var jane = Person();
jane.name = "Jane";

var method = jane.sayName;
method(); // ?

Code block 54

java
class Person {
  sayName() {
    print this.name;
  }
}

var jane = Person();
jane.name = "Jane";

var bill = Person();
bill.name = "Bill";

bill.sayName = jane.sayName;
bill.sayName(); // ?

Code block 55

text
    define(stmt.name);

Code block 56

text
    for (Stmt.Function method : stmt.methods) {
      FunctionType declaration = FunctionType.METHOD;
      resolveFunction(method, declaration); 
    }

Code block 57

java
    return null;

Code block 58

text
    NONE,

Code block 59

text
    FUNCTION,

Code block 60

text
    METHOD

Code block 61

text
  }

Code block 62

text
    environment.define(stmt.name.lexeme, null);

Code block 63

java
    Map<String, LoxFunction> methods = new HashMap<>();
    for (Stmt.Function method : stmt.methods) {
      LoxFunction function = new LoxFunction(method, environment);
      methods.put(method.name.lexeme, function);
    }

    LoxClass klass = new LoxClass(stmt.name.lexeme, methods);

Code block 64

text
    environment.assign(stmt.name, klass);

Code block 65

text
  final String name;

Code block 66

java
  private final Map<String, LoxFunction> methods;

  LoxClass(String name, Map<String, LoxFunction> methods) {
    this.name = name;
    this.methods = methods;
  }

Code block 67

java
  @Override
  public String toString() {

Code block 68

java
  Object get(Token name) {
    if (fields.containsKey(name.lexeme)) {
      return fields.get(name.lexeme);
    }

Code block 69

java
    LoxFunction method = klass.findMethod(name.lexeme);
    if (method != null) return method;

Code block 70

java
    throw new RuntimeError(name, 
        "Undefined property '" + name.lexeme + "'.");

Code block 71

java
  LoxFunction findMethod(String name) {
    if (methods.containsKey(name)) {
      return methods.get(name);
    }

    return null;
  }

Code block 72

java
class Bacon {
  eat() {
    print "Crunch crunch crunch!";
  }
}

Bacon().eat(); // Prints "Crunch crunch crunch!".

Code block 73

java
class Egotist {
  speak() {
    print this;
  }
}

var method = Egotist().speak;
method();

Code block 74

java
class Cake {
  taste() {
    var adjective = "delicious";
    print "The " + this.flavor + " cake is " + adjective + "!";
  }
}

var cake = Cake();
cake.flavor = "German chocolate";
cake.taste(); // Prints "The German chocolate cake is delicious!".

Code block 75

java
class Thing {
  getCallback() {
    fun localFunction() {
      print this;
    }

    return localFunction;
  }
}

var callback = Thing().getCallback();
callback();

Code block 76

java
      "Set      : Expr object, Token name, Expr value",

Code block 77

java
      "This     : Token keyword",

Code block 78

java
      "Unary    : Token operator, Expr right",

Code block 79

java
      return new Expr.Literal(previous().literal);
    }

Code block 80

java
    if (match(THIS)) return new Expr.This(previous());

Code block 81

java
    if (match(IDENTIFIER)) {

Code block 82

java
  @Override
  public Void visitThisExpr(Expr.This expr) {
    resolveLocal(expr, expr.keyword);
    return null;
  }

Code block 83

text
    define(stmt.name);

Code block 84

text
    beginScope();
    scopes.peek().put("this", true);

Code block 85

text
    for (Stmt.Function method : stmt.methods) {

Code block 86

text
    }

Code block 87

text
    endScope();

Code block 88

java
    return null;

Code block 89

java
    LoxFunction method = klass.findMethod(name.lexeme);

Code block 90

java
    if (method != null) return method.bind(this);

Code block 91

java
    throw new RuntimeError(name, 
        "Undefined property '" + name.lexeme + "'.");

Code block 92

java
  LoxFunction bind(LoxInstance instance) {
    Environment environment = new Environment(closure);
    environment.define("this", instance);
    return new LoxFunction(declaration, environment);
  }

Code block 93

java
  @Override
  public Object visitThisExpr(Expr.This expr) {
    return lookUpVariable(expr.keyword, expr);
  }

Code block 94

text
print this;

Code block 95

text
fun notAMethod() {
  print this;
}

Code block 96

text
  }

Code block 97

java
  private enum ClassType {
    NONE,
    CLASS
  }

  private ClassType currentClass = ClassType.NONE;

Code block 98

java
  void resolve(List<Stmt> statements) {

Code block 99

java
  public Void visitClassStmt(Stmt.Class stmt) {

Code block 100

text
    ClassType enclosingClass = currentClass;
    currentClass = ClassType.CLASS;

Code block 101

text
    declare(stmt.name);

Code block 102

text
    endScope();

Code block 103

text
    currentClass = enclosingClass;

Code block 104

java
    return null;

Code block 105

java
  public Void visitThisExpr(Expr.This expr) {

Code block 106

java
    if (currentClass == ClassType.NONE) {
      Lox.error(expr.keyword,
          "Can't use 'this' outside of a class.");
      return null;
    }

Code block 107

text
    resolveLocal(expr, expr.keyword);

Code block 108

java
                     List<Object> arguments) {
    LoxInstance instance = new LoxInstance(this);

Code block 109

java
    LoxFunction initializer = findMethod("init");
    if (initializer != null) {
      initializer.bind(instance).call(interpreter, arguments);
    }

Code block 110

java
    return instance;

Code block 111

java
  public int arity() {

Code block 112

java
    LoxFunction initializer = findMethod("init");
    if (initializer == null) return 0;
    return initializer.arity();

Code block 113

text
  }

Code block 114

java
class Foo {
  init() {
    print this;
  }
}

var foo = Foo();
print foo.init();

Code block 115

java
      return returnValue.value;
    }

Code block 116

java
    if (isInitializer) return closure.getAt(0, "this");

Code block 117

java
    return null;

Code block 118

java
  private final Environment closure;

Code block 119

java
  private final boolean isInitializer;

  LoxFunction(Stmt.Function declaration, Environment closure,
              boolean isInitializer) {
    this.isInitializer = isInitializer;

Code block 120

text
    this.closure = closure;
    this.declaration = declaration;

Code block 121

java
  public Void visitFunctionStmt(Stmt.Function stmt) {

Code block 122

java
    LoxFunction function = new LoxFunction(stmt, environment,
                                           false);

Code block 123

text
    environment.define(stmt.name.lexeme, function);

Code block 124

text
    for (Stmt.Function method : stmt.methods) {

Code block 125

java
      LoxFunction function = new LoxFunction(method, environment,
          method.name.lexeme.equals("init"));

Code block 126

text
      methods.put(method.name.lexeme, function);

Code block 127

text
    environment.define("this", instance);

Code block 128

java
    return new LoxFunction(declaration, environment,
                           isInitializer);

Code block 129

text
  }

Code block 130

java
class Foo {
  init() {
    return "something else";
  }
}

Code block 131

text
    FUNCTION,

Code block 132

text
    INITIALIZER,

Code block 133

text
    METHOD

Code block 134

text
      FunctionType declaration = FunctionType.METHOD;

Code block 135

java
      if (method.name.lexeme.equals("init")) {
        declaration = FunctionType.INITIALIZER;
      }

Code block 136

text
      resolveFunction(method, declaration);

Code block 137

java
    if (stmt.value != null) {

Code block 138

java
      if (currentFunction == FunctionType.INITIALIZER) {
        Lox.error(stmt.keyword,
            "Can't return a value from an initializer.");
      }

Code block 139

text
      resolve(stmt.value);

Code block 140

java
class Foo {
  init() {
    return;
  }
}

Code block 141

text
    } catch (Return returnValue) {

Code block 142

java
      if (isInitializer) return closure.getAt(0, "this");

Code block 143

java
      return returnValue.value;

Code block 144

java
class Math {
  class square(n) {
    return n * n;
  }
}

print Math.square(3); // Prints "9".

Code block 145

java
class Circle {
  init(radius) {
    this.radius = radius;
  }

  area {
    return 3.141592653 * this.radius * this.radius;
  }
}

var circle = Circle(4);
print circle.area; // Prints roughly "50.2655".

Code block 146

text
power = breadth × ease ÷ complexity

参考资料

  • 原文:Classes
  • 系列索引
  • Robert Nystrom, Crafting Interpreters,© 2015–2021
← 返回列表
← 上一篇 Resolving and Binding:静态作用域与变量解析 下一篇 → Inheritance:superclass、subclass 与 super call

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论