熟悉 JavaScript 的朋友应该会知道,如果一个实例的方法中用了this,那把这个方法单独拿出来执行是会报错的。
class Test{
constructor(value){
this.value=value;
};
myTestMethod(){
console.log(this.value);
}
}
var a=new Test(1);
a.myTestMethod();
// 1
var tmp=a.myTestMethod;
tmp();
//VM347:7 Uncaught TypeError: Cannot read properties of undefined (reading 'value')
// at myTestMethod (<anonymous>:7:22)
// at <anonymous>:15:1
但是在 Dart 中,实例的方法是一个闭包,始终可以获取实例的内部变量。
class Test{
int value;
Test(this.value);
myTestMethod(){
print(value);
}
}
void main() {
Test a=new Test(1);
a.myTestMethod();
// 1
var tmp=a.myTestMethod;
tmp();
// 1
print(tmp);
//Closure 'myTestMethod$0' of Instance of 'Test'
}