gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:13:55 25 4
gpt4 key购买 nike

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

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];
}
}

接下来,我尝试从“main”函数调用“fullName”函数:
void main() {
print(person("Rob", "Rock").fullName());
}

但它产生了这个错误:
Uncaught TypeError: Cannot read property 'fullName$0' of undefined

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

最佳答案

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

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

或返回:

void main() {
person(firstName, lastName) => () => "firstName: $firstName"
"lastName: $lastName";
print(person("Rob", "Rock")());
}

如果你想要这个语法 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());
}

关于dart - 在 Dart 编程语言中调用嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24235190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com