3

JavaScript 计算属性

 1 year ago
source link: https://www.myfreax.com/javascript-computed-property/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
JavaScript 计算属性

JavaScript 计算属性

在本教程中,您将了解 ES6 引入的 JavaScript 计算属性。

JavaScript 计算属性简介

ES6 允许您在 [] 中括号使用表达式。然后它将表达式的结果用作对象的属性名称。例如:

let propName = 'c';

const rank = {
  a: 1,
  b: 2,
  [propName]: 3,
};

console.log(rank.c); // 3

在此示例中,[propName]rank 对象的计算属性。属性名称是 propName 变量的值。

当您访问 rank 对象的 c 属性时,JavaScript 计算 propName 并返回该属性的值。

对象字面量一样,您可以使用计算属性为getter 和 setter。例如:

let name = 'fullName';

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get [name]() {
    return `${this.firstName} ${this.lastName}`;
  }
}

let person = new Person('John', 'Doe');
console.log(person.fullName);
John Doe

代码是如何运行的:

get[name]Person 类的 getter 的计算属性名称。在运行时,当您访问fullName属性时,person 对象会调用 getter 并返回全名。

  • 计算属性允许您使用表达式的值作为对象的属性名称。

微信公众号

支付宝打赏

myfreax 淘宝打赏

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK