在 Dart 编程语言中调用嵌套函数

And*_*een 4 dart

我在这里定义了一个内部函数:

person(firstName, lastName){
    fullName(){ //Is it possible to invoke this function outside the 'person' function?
        return firstName + " "  + lastName;
    }
    firstInitial(){
        return firstName[0];
    }
    lastInitial(){
        return lastName[0];
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,我尝试从“main”函数调用“fullName”函数:

void main() {
  print(person("Rob", "Rock").fullName());
}
Run Code Online (Sandbox Code Playgroud)

但它产生了这个错误:

Uncaught TypeError: Cannot read property 'fullName$0' of undefined
Run Code Online (Sandbox Code Playgroud)

是否可以在定义函数的范围之外调用内部函数?

JAr*_*Are 5

您可以在封闭块之外声明该函数:

void main() {
  var fullName;
  person(firstName, lastName){
      fullName = () => "firstName: $firstName lastName: $lastName";
  }
  person("Rob", "Rock");
  print(fullName());
}
Run Code Online (Sandbox Code Playgroud)

或返回它:

void main() {
  person(firstName, lastName) => () => "firstName: $firstName"
                                       "lastName: $lastName";
  print(person("Rob", "Rock")());
}
Run Code Online (Sandbox Code Playgroud)

如果您想要这种语法,person("Rob", "Rock").fullName()您可以返回类实例:

class Res{
  var _firstName, _lastName;
  Res(this._firstName, this._lastName);
  fullName() => "firstName: $_firstName lastName: $_lastName";
}
void main() {
  person(firstName, lastName) => new  Res(firstName,lastName);
  print(person("Rob", "Rock").fullName());
}
Run Code Online (Sandbox Code Playgroud)