-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLoxClass.js
47 lines (38 loc) · 1.01 KB
/
LoxClass.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const LoxInstance = require('./LoxInstance');
class LoxClass {
constructor(name, superclass, methods) {
this.name = name;
this.superclass = superclass;
this.methods = methods;
this.toString = this.toString.bind(this);
this.call = this.call.bind(this);
this.arity = this.arity.bind(this);
this.findMethod = this.findMethod.bind(this);
}
findMethod(name) {
if (this.methods.has(name)) {
return this.methods.get(name);
}
if (this.superclass !== null) {
return this.superclass.findMethod(name);
}
return null;
}
call(interpreter, args) {
const instance = new LoxInstance(this);
const initializer = this.findMethod('init');
if (initializer !== null) {
initializer.bind(instance).call(interpreter, args);
}
return instance;
}
arity() {
const initializer = this.findMethod('init');
if (initializer === null) return 0;
return initializer.arity();
}
toString() {
return this.name;
}
}
module.exports = LoxClass;