从函数中返回对象可以通过以下几种方式实现:
function createPerson() {
return { name: 'John', age: 30 };
}
const person = createPerson();
console.log(person); // { name: 'John', age: 30 }
function Person(name, age) {
this.name = name;
this.age = age;
}
function createPerson(name, age) {
return new Person(name, age);
}
const person = createPerson('John', 30);
console.log(person); // Person { name: 'John', age: 30 }
function createPerson(name, age) {
return {
name: name,
age: age,
sayHello: function() {
console.log('Hello, my name is ' + this.name);
}
};
}
const person = createPerson('John', 30);
console.log(person); // { name: 'John', age: 30, sayHello: [Function] }
person.sayHello(); // Hello, my name is John
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log('Hello, my name is ' + this.name);
}
}
function createPerson(name, age) {
return new Person(name, age);
}
const person = createPerson('John', 30);
console.log(person); // Person { name: 'John', age: 30 }
person.sayHello(); // Hello, my name is John
这些方法可以根据具体的需求选择使用。返回对象可以方便地封装和传递数据,以及调用对象的方法。
领取专属 10元无门槛券
手把手带您无忧上云