fbpx

Object Trong JavaScript Và Các Kiến Thức Bạn Cần Phải Nắm Vững

object trong javascript

Object trong JavaScript (đối tượng trong JavaScript) là tập hợp của các cặp key-value. Và property là tên gọi của mỗi cặp key-value.

Property trong object

Giá trị (value) của một property có thể thuộc bất kỳ kiểu dữ liệu như: string, number, object, function,….

Khi giá trị của một property là function thì tên gọi của nó là method.

Method trong object

Có nhiều cách để khởi tạo một object trong JavaScript (đối tượng trong JavaScript). Cách phổ biến nhất là sử dụng cú pháp object literal.

Sau đây là ví dụ khởi tạo một object bằng cú pháp object literal:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let empty = {};
let empty = {};
let empty = {};

Để thêm property cho object, bạn hãy sử dụng key: value bên trong cặp dấu ngoặc nhọn. Ví dụ:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'Nguyen',
lastName: 'Hung'
};
let person = { firstName: 'Nguyen', lastName: 'Hung' };
let person = {
    firstName: 'Nguyen',
    lastName: 'Hung'
};

Ở ví dụ trên, object person có hai property firstNamelastName với các giá trị tương ứng là 'Nguyen''Hung'.

Dấu phẩy (,) dùng để ngăn cách các property với nhau.

Xem thêm: JavaScript là gì?

1. Truy cập property (Accessing property)

Để truy cập một property, bạn có thể sử dụng một trong hai cách sau:

  • The dot notation (.)
  • The array-like notation ([])

The dot notation (.)

Sau đây là ví dụ sử dụng dot notation (.) để truy cập một property của object:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'Nguyen',
lastName: 'Hung'
};
console.log(person.firstName);
console.log(person.lastName);
let person = { firstName: 'Nguyen', lastName: 'Hung' }; console.log(person.firstName); console.log(person.lastName);
let person = {
    firstName: 'Nguyen',
    lastName: 'Hung'
};

console.log(person.firstName);
console.log(person.lastName);

Ở ví dụ trên, sau khi khởi tạo object person, thì mình đã log ra giá trị của các property firstNamelastName.

Array-like notation ([])

Sau đây là ví dụ sử dụng array-like notation ([]) để truy cập một property của object:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'Nguyen',
lastName: 'Hung'
};
console.log(person['firstName']);
console.log(person['lastName']);
let person = { firstName: 'Nguyen', lastName: 'Hung' }; console.log(person['firstName']); console.log(person['lastName']);
let person = {
    firstName: 'Nguyen',
    lastName: 'Hung'
};

console.log(person['firstName']);
console.log(person['lastName']);

Trong trường hợp tên property có khoảng cách, bạn cần đặt tên property ở giữa cặp dấu ngoặc kép.

Mình sẽ tạo object address có property là 'building no' để bạn thấy rõ hơn:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let address = {
'building no': 5360,
street: '5B Pho Quang',
district: 'Tan Binh',
city: 'Ho Chi Minh'
};
let address = { 'building no': 5360, street: '5B Pho Quang', district: 'Tan Binh', city: 'Ho Chi Minh' };
let address = {
    'building no': 5360,
    street: '5B Pho Quang',
    district: 'Tan Binh',
    city: 'Ho Chi Minh'
};

Để truy cập property 'building no', bạn cần phải sử dụng array-like-notation:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
address['building no'];
address['building no'];
address['building no'];

Nếu bạn sử dụng dot notation, chương trình sẽ báo lỗi:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
address.'building no';
address.'building no';
address.'building no';

Error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
SyntaxError: Unexpected string
SyntaxError: Unexpected string
SyntaxError: Unexpected string

Lưu ý: Bạn không nên sử dụng khoảng cách cho tên của property.

Khi bạn truy cập một property không tồn tại trong object thì kết quả trả về sẽ là undefined. Ví dụ:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(address.country);
console.log(address.country);
console.log(address.country);

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
undefined
undefined
undefined

2. Thay đổi giá trị (value) của property

Để thay đổi giá trị của một property, bạn có thể sử dụng toán tử gán (=). Ví dụ:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'Nguyen',
lastName: 'Hung'
};
// Thay đổi giá trị property firstName
person.firstName = 'Tran';
console.log(person);
let person = { firstName: 'Nguyen', lastName: 'Hung' }; // Thay đổi giá trị property firstName person.firstName = 'Tran'; console.log(person);
let person = {
    firstName: 'Nguyen',
    lastName: 'Hung'
};

// Thay đổi giá trị property firstName
person.firstName = 'Tran';
console.log(person);

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{ firstName: 'Tran', lastName: 'Hung' }
{ firstName: 'Tran', lastName: 'Hung' }
{ firstName: 'Tran', lastName: 'Hung' }

Ở ví dụ trên, mình đã thay đổi giá trị của property firstName từ 'Nguyen' sang 'Tran'.

3. Thêm một property mới vào object

Không giống những object trong các ngôn ngữ lập trình khác như Java hoặc C++, bạn có thể thêm mới property sau khi khởi tạo object trong JavaScript.

Mình sẽ thêm một property age cho object person và gán giá trị cho nó là 20 ở câu lệnh sau:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
person.age = 20;
person.age = 20;
person.age = 20;

4. Xóa một property của object

Bạn sử dụng toán tử delete để xoá một property bất kì.

Mình sẽ tiến hành xoá property age của object person mà đã thêm trước đó:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
delete person.age;
delete person.age;
delete person.age;

Bạn có thể truy cập vào lại property age để kiểm tra xem nó đã bị xoá hay chưa, thì lúc này kết quả sẽ là undefined:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(person.age);
console.log(person.age);
console.log(person.age);

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
undefined
undefined
undefined

5. Kiểm tra một property có tồn tại hay không

Bạn sử dụng toán tử in để kiểm tra một property có tồn tại trong object hay không:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
propertyName in objectName
propertyName in objectName
propertyName in objectName

Toán tử in sẽ trả kết quả là true nếu propertyName tồn tại trong objectName.

Ở ví dụ sau đây, mình sẽ khởi tạo một object employee và sử dụng toán tử in để kiểm tra xem property ssnemployeeId có tồn tại trong object hay không:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let employee = {
firstName: Nguyen,
lastName: Hung,
employeeId: 1
};
console.log('ssn' in employee);
console.log('employeeId' in employee);
let employee = { firstName: Nguyen, lastName: Hung, employeeId: 1 }; console.log('ssn' in employee); console.log('employeeId' in employee);
let employee = {
    firstName: Nguyen,
    lastName: Hung,
    employeeId: 1
};

console.log('ssn' in employee);
console.log('employeeId' in employee);

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
false
true
false true
false
true

6. Sử dụng for…in để lặp qua các property của object

Để lặp qua tất cả các property của object, bạn sử dụng câu lệnh for...in:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for (let key in object) {
// ...
}
for (let key in object) { // ... }
for (let key in object) {
    // ...
}

Ở ví dụ sau, mình sẽ tạo object website và sau đó dùng câu lệnh for...in để lặp qua các property của object website:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let website = {
title: 'JavaScript Tutorial',
url: 'https://letdiv.com/khoa-hoc-javascript/',
tags: ['es6', 'javascript', 'dom']
};
for (const key in website) {
console.log(key);
}
let website = { title: 'JavaScript Tutorial', url: 'https://letdiv.com/khoa-hoc-javascript/', tags: ['es6', 'javascript', 'dom'] }; for (const key in website) { console.log(key); }
let website = {
    title: 'JavaScript Tutorial',
    url: 'https://letdiv.com/khoa-hoc-javascript/',
    tags: ['es6', 'javascript', 'dom']
};

for (const key in website) {
    console.log(key);
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
'title'
'url'
'tags'
'title' 'url' 'tags'
'title'
'url'
'tags'

7. Method

Khi property của object là function thì tên gọi của nó là method. Có thể xem method là hành động (action) của một object:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'John',
lastName: 'Doe'
};
// greet method
person.greet = function () {
console.log('Hello!');
}
person.greet();
let person = { firstName: 'John', lastName: 'Doe' }; // greet method person.greet = function () { console.log('Hello!'); } person.greet();
let person = {
    firstName: 'John',
    lastName: 'Doe'
};

// greet method
person.greet = function () {
    console.log('Hello!');
}
person.greet();

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Hello!
Hello!
Hello!

Ví dụ trên, mình gán giá trị cho property greet là một function. Ở đây, mình sử dụng function expression để tạo function.

Sau đó mình thực thi function này bằng câu lệnh person.greet().

Bên cạnh việc sử dụng function expression, bạn có thể định nghĩa một function thông thường bên ngoài object như sau:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'John',
lastName: 'Doe'
};
function greet() {
console.log('Hello, World!');
}
person.greet = greet;
person.greet();
let person = { firstName: 'John', lastName: 'Doe' }; function greet() { console.log('Hello, World!'); } person.greet = greet; person.greet();
let person = {
    firstName: 'John',
    lastName: 'Doe'
};

function greet() {
    console.log('Hello, World!');
}

person.greet = greet;

person.greet();

Ở đoạn code trên, mình định nghĩa một function có tên là greet.

Tiếp theo, mình sử dụng biểu thức person.greet = greet để gán function greet cho property greet của object person.

8. Method Shorthand

Như đã biết, bạn có thể định nghĩa method của một object bằng cách sử dụng cú pháp object literal:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'John',
lastName: 'Doe',
greet: function () {
console.log('Hello, World!');
}
};
let person = { firstName: 'John', lastName: 'Doe', greet: function () { console.log('Hello, World!'); } };
let person = {
    firstName: 'John',
    lastName: 'Doe',
    greet: function () {
        console.log('Hello, World!');
    }
};

Bên cạnh đó, bạn cũng có thể định nghĩa method ngắn gọn hơn thông qua cú pháp concise method của ES6:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'John',
lastName: 'Doe',
greet() {
console.log('Hello, World!');
}
};
person.greet();
let person = { firstName: 'John', lastName: 'Doe', greet() { console.log('Hello, World!'); } }; person.greet();
let person = {
    firstName: 'John',
    lastName: 'Doe',
    greet() {
        console.log('Hello, World!');
    }
};

person.greet();

Cú pháp này trông gọn gàng và ít dài dòng hơn nhiều!

9. The this value

Làm thế nào bạn có thể truy cập đến một property bên trong method của object?

Ví dụ, bạn đang định nghĩa method getFullName cho object person để trả về tên đầy đủ của một người. Vì vậy method này phải trả kết quả bằng cách ghép firstNamelastName lại với nhau.

Để truy cập property firstNamelastName bên trong method getFullName thì mình sử dụng keyword this.

Keyword this tham chiếu đến object person. Do đó, bạn có thể truy cập property của object thông qua this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
this.propertyName;
this.propertyName;
this.propertyName;

Sau đây, mình sẽ viết đoạn code sử dụng this bên trong method getFullName() để bạn hiểu rõ hơn:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let person = {
firstName: 'John',
lastName: 'Doe',
greet: function () {
console.log('Hello, World!');
},
getFullName: function () {
return this.firstName + ' ' + this.lastName;
}
};
console.log(person.getFullName());
let person = { firstName: 'John', lastName: 'Doe', greet: function () { console.log('Hello, World!'); }, getFullName: function () { return this.firstName + ' ' + this.lastName; } }; console.log(person.getFullName());
let person = {
    firstName: 'John',
    lastName: 'Doe',
    greet: function () {
        console.log('Hello, World!');
    },
    getFullName: function () {
        return this.firstName + ' ' + this.lastName;
    }
};


console.log(person.getFullName());

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
'John Doe'
'John Doe'
'John Doe'

Ghi nhớ

  • Object là tập hợp các cặp key-value.
  • Sử dụng dot notation (.) hoặc array-like notation ([]) để truy cập property của object.
  • Toán tử delete dùng để xoá property của object.
  • Toán tử in dùng để kiểm tra property có tồn tại trong object hay không.
  • for...in dùng để lặp qua các property của object.
  • Khi giá trị của một property là function thì tên gọi của nó là method.
  • Sử dụng this bên trong method để truy cập property của object.

Kết Luận

Thông qua bài viết này, mình mong bạn sẽ biết rõ hơn đối tượng trong javascript là gì, đồng thời có thể hiểu được các cú pháp cơ bản nhất dùng để thao tác với object.

Tiếp theo, mình sẽ giúp các bạn có cái nhìn chi tiết hơn về property và các attributes của nó như configurable, enumerable, writable, get, set và value.

Chi tiết: https://letdiv.com/javascript-object-property/

Tùng ViO

Tùng ViO

Mình là Tùng ViO, hiện tại đang là Founder và cũng là giảng viên tại LetDiv. Rất hân hạnh được làm quen với bạn!