Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách thêm và truy cập phương thức đối tượng JavaScript

Thêm và truy cập phương thức (method) của Object

Trong JavaScript, phương thức đơn giản là hàm được gán làm giá trị của một property trong object. Có thể thêm khi tạo object hoặc động sau khi tạo.

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Object Methods</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 18px; font-weight: 500; color: green; font-family: monospace; }
        button { padding: 8px 16px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Thêm và Truy cập Phương thức Object JavaScript</h1>
    <div class="result"></div>
    <button class="btn-demo">KIỂM TRA</button>
    <h3>Nhấn nút để thêm và gọi phương thức object</h3>

    <script>
        const resEle = document.querySelector(".result");
        const btn = document.querySelector(".btn-demo");

        // Object ban đầu không có phương thức
        const obj = {
            firstName: 'Rohan',
            lastName: 'Sharma',
            age: '22'
        };

        btn.addEventListener("click", () => {
            // 1. Thêm phương thức động (function expression)
            obj.welcome = function() {
                return 'Chào mừng ' + this.firstName + ' ' + this.lastName;
            };

            // 2. Truy cập phương thức (không gọi - lấy định nghĩa)
            resEle.innerHTML = 'Thêm phương thức welcome: ' + obj.welcome + '<br>';

            // 3. Gọi phương thức (có dấu ngoặc)
            resEle.innerHTML += 'Gọi phương thức welcome(): ' + obj.welcome() + '<br>';
        });
    </script>
</body>
</html>

Các cách định nghĩa phương thức

1. Trong object literal (ES6 shorthand) - Khuyến nghị

const user = {
    name: 'John',
    // Method shorthand (ES6)
    greet() {
        return `Hello, ${this.name}!`;
    },
    // Arrow function (KHÔNG có this riêng)
    greetArrow: () => `Hello, ${this.name}!` // this = window/undefined
};

2. Thêm động sau khi tạo object

const user = { name: 'John' };

// Function expression
user.sayHi = function() { return 'Hi ' + this.name; };

// Arrow function (cẩn thận với this)
user.sayHiArrow = () => 'Hi ' + user.name; // dùng user thay vì this

3. Object.defineProperty() - Kiểm soát chi tiết

Object.defineProperty(user, 'id', {
    value: 1,
    writable: false,
    enumerable: true,
    configurable: false
});

Truy cập phương thức

const obj = {
    value: 42,
    getValue() { return this.value; }
};

// Gọi trực tiếp
obj.getValue(); // 42

// Gán cho biến -> MẤT this context
const fn = obj.getValue;
fn(); // undefined (this = window/undefined)

// Giữ this với bind()
const boundFn = obj.getValue.bind(obj);
boundFn(); // 42

// Hoặc arrow function wrapper
const arrowFn = () => obj.getValue();
arrowFn(); // 42

Method vs Function - Sự khác biệt then chốt

function standalone() {
    console.log(this); // window/undefined
}

const obj = {
    method() {
        console.log(this); // obj
    }
};

standalone();     // Function invocation
obj.method();     // Method invocation <- this = obj