飞镖的静态方法和类方法的区别

时间:2020-06-13 09:54:11

标签: dart

我对飞镖并不陌生。我试图了解这两种方法之间的区别。两种方法是不同的还是相同的?我应该在哪里使用另一个?有人可以向我解释吗?

class A {
  A.executor1() {
    print('executor one is called');
  }

  static executor2() {
    print('executor two is called');
  }
}

同时创建新实例不需要方法调用吗?两者都使用类名来调用。

void main() {
  A.executor1(); // Will print "executor one is called"
  A.executor2(); // Will print "executor two is called"
}

2 个答案:

答案 0 :(得分:1)

A.executor1()是一个命名构造函数。 static executor2()是静态方法。

使用IDE(或dartpad.dev),将光标放在每个method上时,您可以看到不同的返回类型:

void main() {
  A.executor1(); // (new) A A.executor1()
  A.executor2(); // dynamic executor2()
}

答案 1 :(得分:0)

可以在不创建类实例的情况下调用

static方法。 executor1可以访问this,依此类推,因为它已附加到实际实例上,但是static方法却没有,因为它们没有附加到任何东西上。

考虑(使用Java语言):

class Bicycle {
  static numWheels = 2;
  
  constructor(color) {
    this.color = color;
  }
  
  static numberOfWheels() {
    console.log(`Every bike has ${this.numWheels} wheels.`);
  }
  
  myColor() {
    console.log(`This bike is ${this.color}.`);
  }
}

// property of an instance
new Bicycle('red').myColor();

// available for anyone!
Bicycle.numberOfWheels();

相关问题