Create an Object

Có ba cách để tạo một object:

// Literal
const dog = {}
 
// Constructor
const cat = new Object()
 
// Static method
const horse = Object.create({})

Khai báo và truy xuất thuộc tính:

const person = {
  name: "Quân", // string
  age: 20, // number
  skills: ["HTML", "CSS", "JavaScript"], // array
  isMarried: false, // boolean
  techs: {
    fe: "ReactJS",
    be: "NodeJS",
  }, // nested object
  isMarried: true, // this will replace the first "isMarried" property
  "full-name": "Lê Minh Quân", // key can be put in the quotes like this
}
 
console.log(person.name) // "Quân"
console.log(person["full-name"]) // "Lê Minh Quân"

Khai báo và gọi sử dụng phương thức:

const person = {
  name: "Quan",
 
  // ❌ Wrong, method can not be an arrow function because arrow function doesn't have context
  getName: () => {
    return this.name // 'this' is undefined
  },
 
  getName: function () {
    return this.name
  },
 
  // Shortform
  getName() {
    return this.name
  },
}
 
console.log(person.getName()) // "Quan"

Để truy xuất đến thuộc tính của đối tượng bên trong thân hàm của phương thức, cần phải dùng đến từ khóa this1.

Getter and Setter

Một getter trong đối tượng tương tự như phương thức thông thường nhưng có thêm từ khóa get phía trước. Khi gọi sử dụng, ta không cần dùng toán tử ().

const person = {
  firstName: "Quan",
  lastName: "Le",
  age: 21,
 
  get name() {
    return `${this.firstName} ${this.lastName}`
  },
}
 
// Do not use () when call getter
console.log(person.name) // "Quan Le"

Setter thì có thêm từ khóa set và sử dụng toán tử gán bằng để gán giá trị cho thuộc tính.

const person = {
  firstName: "Quan",
  lastName: "Le",
  age: 21,
 
  get name() {
    return `${this.firstName} ${this.lastName}`
  },
  set setFirstName(firstName) {
    this.firstName = firstName
  },
}
 
// Call setter without (), followed by = operator
person.setFirstName = "Kwan"
 
console.log(person.name) // "Kwan Le"

Add Properties to an Existing Object

Ta cũng có thể khai báo các thuộc tính hoặc phương thức chưa có trong đối tượng và gán giá trị cho chúng. Các thuộc tính mới này sẽ được thêm vào đối tượng.

const person = {
  name: "Quân",
  age: 20,
}
 
person.hair = "curly"
person.getAge = function () {
  return this.age
}
person.undef
 
console.log(person.hair) // "curly"
console.log(person.getAge()) // 20
console.log(person.undef) // undefined

Thậm chí, ta cũng có thể thêm một thuộc tính hay đối tượng vào lớp đối tượng mặc định của JS.

Chẳng hạn, thêm hàm capitalize giúp viết hoa chữ cái đầu của chuỗi vào lớp String:

String.prototype.capitalize = function () {
  return this.at(0).toUpperCase() + this.slice(1)
}
 
console.log("hello world".capitalize()) // "Hello world"

Object in a Template String

Không thể in ra một template string chứa một object:

const object = {
  "key-1": 1,
  "key-2": 2,
}
 
console.log(object) // {"key-1": 1, "key-2": 2}
console.log(`${object}`) // [object Object]

Ta có thể dùng lớp JSON để giải quyết vấn đề này như sau:

const object = {
  "key-1": 1,
  "key-2": 2,
}
 
console.log(object) // {"key-1": 1, "key-2": 2}
console.log(`${JSON.stringify(object)}`) // {"key-1": 1, "key-2": 2}

Property Deletion

Sử dụng từ khóa delete để xóa thuộc tính hoặc phương thức.

const pc = {
  // Properties
  ram: 16,
  cpu: "intel",
  vga: "1050",
 
  // Methods
  getRam() {
    return this.ram
  },
}
 
delete pc.ram
delete pc.getRam
 
console.log(pc) // {cpu: 'intel', vga: '1050'}
pc.getRam() // "TypeError: pc.getRam is not a function"

ES6

Property Initializer

Trước ES6, khi cần tạo một object với các thuộc tính là các biến có sẵn, ta sẽ làm như sau:

let a = 1
let b = 2
 
const object = {
  a: a,
  b: b,
}
 
console.log(object) // {a: 1, b: 2}

Tuy nhiên, ES6 hỗ trợ một tính năng mới cho phép chúng ta tạo object từ biến cục bộ mà không cần gán giá trị cho các thuộc tính:

let a = 1
let b = 2
 
const object = {
  a,
  b,
}
 
console.log(object) // {a: 1, b: 2}

Set Object Key by Variable

Ta có thể sử dụng một giá trị của biến làm tên property:

let key = "name"
 
const object = {
  [key]: "Quan",
}
 
console.log(object) // {name: "Quan"}

Resources

Footnotes

  1. xem thêm JS this Keyword