嵌套函数:调用时输出"未定义"的函数



我做了一个箭头函数如下,嵌套在getdata函数中,当我调用getdata函数时,它会输出undefined,我做错了什么?

let person = {
name: "Mario",
age: 30,
salary: 5555,
getdata: function () {
welcome = () => {
return `hello: ${this.name} your age is ${this.salary}`
};
},
}
console.log(person.getdata())

我想你的意思是这样做。

let person = {
name: "Mario",
age: 30,
salary: 5555,
getdata:  () => {
return `hello: ${this.name} your age is ${this.salary}`
};
}
let person = {
name: "Mario",
age: 30,
salary: 5555,
getdata: function () {
return {
welcome: function() {
return `hello: ${this.name} your age is ${this.salary}`
}
}

},
}

这将返回所需的结果:

person.getdata().welcome()

由于getData()只是一个定义另一个函数但不返回任何内容的函数,因此调用它的返回值是undefined。但是,如果你删除嵌套函数,只返回你想要的数据,你将得到一个返回值:

let person = {
name: "Mario",
age: 30,
salary: 5555,
getdata: function () {
return  `hello: ${this.name} your age is ${this.salary}`
},
}
console.log(person.getdata());

这是因为getdata()没有返回任何内容。它只有一个嵌套函数。如果您只想返回欢迎的内容,这就是您要放置的内容。

let person = {
name: "Mario",
age: 30,
salary: 5555,
getdata: function () {
return `hello: ${this.name} your age is ${this.salary}`
}
}

你不能在静态对象中传递上下文, 解决问题的最佳模式是通过 js 类:

class person {
constructor(data) {
this.info = data;
}
welcome(){
return `hello: ${this.info.name} your age is ${this.info.age}`
}
getSalary(){
return this.info.salary;
}
getAge(){
return this.info.age;
}
}
var mario = {
name: "Mario",
age: 30,
salary: 5555,
}

var data = new person(mario);
console.log(data.welcome());
console.log(data.getSalary());
console.log(data.getAge());

问题是你的getdata函数不返回任何内容。 你想要的是创建一个具有属性getdata的对象person,这是一个返回嵌套对象的函数,该嵌套对象也具有一个属性welcome,这是一个返回字符串的函数。

我认为您要实现的目标如下:

let person = {
name: "Mario",
age: 30,
salary: 5555,
getdata: function () {
return {
welcome: () =>  `hello: ${this.name} your age is ${this.salary}`
}
}
}

所以你可以做到:

console.log(person.getdata().welcome()) //"hello: Mario your age is 5555"

最新更新