我在这里定义了一个内部函数:
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是否有可能在定义函数的作用域之外调用内部函数?
发布于 2014-06-16 00:29:48
您可以在封闭块之外声明函数:
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());
}发布于 2014-06-17 00:26:33
这些函数可以从外部调用,问题是您的程序无法看到它们。您的函数返回void,因此内部函数是不可见的。
但是看起来你想要做的是定义一个类。所以一个更简单的方法就是
class Person {
var firstName, lastName;
Person(this.firstName, this.lastName);
get fullName => "$firstName $lastName";
firstInitial() => firstName[0];
lastInitial() { return lastName[0]; }
}
main() {
print(new Person("Rob", "Rock).fullName);
print(new Person("Robert", "Stone").lastInitial());
}为了举例说明,我为这三个不同的函数使用了三个不同的语法,一个getter,一个lambda和一个完整的函数。
https://stackoverflow.com/questions/24235190
复制相似问题