🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
下一个例子展示了属性常用的访问标识符组合: > The next example shows common access identifier combinations for properties: ~~~ class Main { // 从外部可读取,只在Main中写入 public var ro(default, null):Int; // 从外部写入,只在Main中读取 public var wo(null, default):Int; // 通过 getter 和 setter 访问 // get_x & set_x public var x(get, set):Int; // 通过 getter 读取,不可写入 public var y(get, never):Int; // 被字段 x 需要 function get_x() return 1; // 被字段 x 需要 function set_x(x) return x; // 被字段 y 需要 function get_y() return 1; function new() { var v = x; x = 2; x += 1; } static public function main() { new Main(); } } ~~~ JavaScript 输出帮助我们理解 main 方法中的字段访问被编译为: > The JavaScript output helps understand what the field access in the main-method is compiled to: ~~~ var Main = function() { var v = this.get_x(); this.set_x(2); var _g = this; _g.set_x(_g.get_x() + 1); }; ~~~ 就像说明的,读取访问生成一个get_x()的调用,而写入访问生成 set_x(2)的调用,2即为被赋值到x 的值。 +=生成的方式可能看起来有点奇怪,但是可以通过下面的例子很容易的证明: > As specified, the read access generates a call to get_x(), while the write access generates a call to set_x(2) where 2 is the value being assigned to x. The way the += is being generated might look a little odd at first, but can easily be justified by the following example: ~~~ class Main { public var x(get, set):Int; function get_x() return 1; function set_x(x) return x; public function new() { } static public function main() { new Main().x += 1; } } ~~~ 这里发生的是,字段的表达式部分在main方法中访问x是复杂的:它有潜在的副作用,如本例中Main的构建。因此,编译器不能生成 += 操作符 为 new Main().x = new Main().x+1, 而且必须缓存复杂的表达式到一个局部变量: > What happens here is that the expression part of the field access to x in the main method is complex: It has potential side-effects, such as the construction of Main in this case. Thus, the compiler can not generate the += operationas new Main().x = new Main().x + 1 andhas to cache the complex expression in a local variable: ~~~ Main.main = function() { var _g = new Main(); _g.set_x(_g.get_x() + 1); } ~~~