Class and Inheritance
Neuron Teckid edited this page Mar 21, 2016
·
4 revisions
语法
class CLASS_NAME: BASE_CLASS
CLASS_BODY
其中 CLASS_NAME
为类名; 当类继承其它类时, BASE_CLASS
为基类表达式, 否则此基类名称连同前面的冒号都应省略; CLASS_BODY
为类体, 类体中的成员必须有相同的缩进. 类体只能包括构造函数定义和成员函数定义, 不能有成员/静态变量定义和嵌套的类定义.
构造函数定义以关键字 ctor
, 接内含形参列表的一对括号, 之后可以加上对父类构造函数的调用 (有继承的情况下), 开头定义语法为
ctor (PARAMETERS) SUPER_CONSTRCTOR_CALL
FUNCTION_BODY
形式参数列表不能包含正规异步占位符.
对父类的构造函数调用语法为
super (ARGUMENTS)
一个完整的例子
class Animal
ctor (name)
this.name: name
class Bird: Animal
ctor (name, speed) super (name)
this.speed: speed
初始化 Flatscript 中定义的类型可以不使用前置星号 (在 Flatscript 中使用前置星号操作符替代 Javascript 中的 new
关键字). 并且建议这么做.
如构造前面例子中的 Bird
实例
raven: Bird('Karas', 7)
成员函数定义与普通函数定义语法相同, 区别是, 在成员函数体内可以使用 super
函数调用, 即调用父类的成员函数.
super
函数调用指的是在子类函数体内调用父类的成员函数, 其语法必须是
super.FUNCTION_NAME(ARGUMENTS)
其中 FUNCTION_NAME
为函数名标识符, ARGUMENTS
为参数列表. 以下均为不合法的写法
super['FUNCTION_NAME'](ARGUMENTS)
super(ARGUMENTS) # super is not callable
x: super # ERROR: super is not an expression
# separate into two phases
y: super.FUNCTION_NAME # ERROR: super is not an object
y(ARGUMENTS)
一个完整的例子
class Animal
ctor (name)
this.name: name
func move(distance)
console.log(this.name + ' moved ' + distance + ' meters')
class Bird: Animal
ctor (name, speed) super (name)
this.speed: speed
func move(distance)
if this.speed = 1
return super.move(distance)
console.log(this.name + ' flied ' + distance * this.speed + ' meters')
以上代码中 super.move(distance)
就是调用父类的 move
函数.
将类名作为函数, 调用此函数传入正确的参数即可构造对象. 如以上述 Animal
, Bird
为例
a: Animal('Alice')
a.move(2)
console.log(a.name)
b: Bird('Bob', 3)
b.move(4)
console.log(b.speed)
即构造和调用对象成员.