从调用对象本身而不是其 属性 名称的对象中获取 属性 值
Get a property value from an object calling object itsself instead of its property name
我想知道在 Javascript 中是否有一种方法可以访问对象的 属性 值(使用 getter 正确设置),只需键入其对象名称而无需不得不输入 'object.property'。
到目前为止我尝试的是这样的:
let person = {
get () {return this.name + this.lastname},
name: 'John',
lastname: 'Doe'
}
console.log (person);
但我总是得到整个对象,而不是我想要的 getter 属性。
有任何想法吗?
谢谢!
覆盖.toString()
方法,然后强制将对象转换为字符串,以强制调用.toString()
方法。
像这样:
let person = {
toString: function() {return this.name + " " + this.lastname},
name: 'John',
lastname: 'Doe'
}
console.log('Person: ' + person);
console.log(''+person);
console.log(person.toString());
console.log(person+'');
备注:
- 需要使用
function
关键字以保留上下文(不能使用箭头函数)。
- 这样做:
console.log(person)
仍然会输出对象结构,因为没有任何东西可以强制调用 .toString()
。
首先:None 我提供的选项 完全 您所要求的(以及据我所知无法完成的内容)在 JS 中)。
也就是说,您可以在此处使用 toString()
方法,尽管这仅在您调用 person
的操作需要字符串强制转换时有效。
您还可以随时解构对象,以便只获得所需的属性。
两者都显示在这个例子中:
let p = {
toString: function() { return `${this.name} ${this.lastname}` },
name: 'John',
lastname: 'Doe'
}
// forcing toString() call
console.log(`${p}`);
// logging the actual object
console.log(p);
// using destructuring
const { name, lastname } = p, person = `${name} ${lastname}`;
console.log(person);
或者,您可以使用 Person
class 以及 getter 和解构:
class Person {
constructor(name, lastname) {
this.name = name;
this.lastname = lastname;
}
get person() {
return `${this.name} ${this.lastname}`;
}
}
const { person } = new Person('John', 'Doe');
console.log(person);
我想知道在 Javascript 中是否有一种方法可以访问对象的 属性 值(使用 getter 正确设置),只需键入其对象名称而无需不得不输入 'object.property'。 到目前为止我尝试的是这样的:
let person = {
get () {return this.name + this.lastname},
name: 'John',
lastname: 'Doe'
}
console.log (person);
但我总是得到整个对象,而不是我想要的 getter 属性。 有任何想法吗? 谢谢!
覆盖.toString()
方法,然后强制将对象转换为字符串,以强制调用.toString()
方法。
像这样:
let person = {
toString: function() {return this.name + " " + this.lastname},
name: 'John',
lastname: 'Doe'
}
console.log('Person: ' + person);
console.log(''+person);
console.log(person.toString());
console.log(person+'');
备注:
- 需要使用
function
关键字以保留上下文(不能使用箭头函数)。 - 这样做:
console.log(person)
仍然会输出对象结构,因为没有任何东西可以强制调用.toString()
。
首先:None 我提供的选项 完全 您所要求的(以及据我所知无法完成的内容)在 JS 中)。
也就是说,您可以在此处使用 toString()
方法,尽管这仅在您调用 person
的操作需要字符串强制转换时有效。
您还可以随时解构对象,以便只获得所需的属性。
两者都显示在这个例子中:
let p = {
toString: function() { return `${this.name} ${this.lastname}` },
name: 'John',
lastname: 'Doe'
}
// forcing toString() call
console.log(`${p}`);
// logging the actual object
console.log(p);
// using destructuring
const { name, lastname } = p, person = `${name} ${lastname}`;
console.log(person);
或者,您可以使用 Person
class 以及 getter 和解构:
class Person {
constructor(name, lastname) {
this.name = name;
this.lastname = lastname;
}
get person() {
return `${this.name} ${this.lastname}`;
}
}
const { person } = new Person('John', 'Doe');
console.log(person);