什么":"在dart的类构造函数中意味着什么?

时间:2016-08-25 04:41:26

标签: class oop syntax constructor dart

我正在阅读关于课程的dartlang.org资源,他们注意到以下结构:

es2015

我不太明白的是":"在Point构造函数中以及为什么/何时应该使用它?

1 个答案:

答案 0 :(得分:5)

启动“初始化列表”。

如果你有strOrderArr = strOrderArr + "'upld_id':" + "'" + docid + "', "; strOrderArr = strOrderArr + "'upld_contentvalue':" + "'" + $(item).val() + "'"; 类中的最终字段,那么有不同的方法来初始化它们。

Point

这不起作用

class Point {
  final num x = 3;
  ...
}

class Point {
  final num x;
  constructor(this.x);
}

class Point {
  final num x;
  constructor(num x) : this.x = x * 3;
}

因为无法在构造函数中修改最终字段。

初始化程序列出了一种解决此限制的方法,同时仍符合对象初始化顺序的保证。它在构造函数体之前执行。 这是一种检查或修改(指定默认值)传递参数的方法,然后将它们分配给最终字段并进行一些计算。

在初始化列表中使用class Point { final num x = 3; constructor(num x) { this.x = x * 3; } } 只允许分配给属性,但不能从中读取它们以防止访问尚未初始化的属性。

对超级构造函数的调用也在初始化列表中完成,通常应该是列表中的最后一次调用。

this