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

Định nghĩa alias (bí danh) trong MongoDB Shell

Sử dụng Object.defineProperty trên đối tượng this (global shell context).

Cú pháp

Object.defineProperty(this, 'yourFunctionName', {
    get: function() {
        yourStatement1;
        // ...
        return N;
    },
    enumerable: true,
    configurable: true
});

Gán alias với var:

var anyAliasName = yourFunctionName;

Ví dụ: Tạo hàm hiển thị thông báo

> Object.defineProperty(this, 'displayMessageDemo', {
    get: function() {
        return "Hello MongoDB";
    },
    enumerable: true,
    configurable: true
});

Gán alias

> var myMessage = displayMessageDemo;

Sử dụng alias

> myMessage;

Kết quả: Hello MongoDB

Giải thích: get định nghĩa getter — mỗi lần truy cập displayMessageDemo (hoặc myMessage) sẽ chạy hàm và trả về giá trị. enumerable: true cho phép liệt kê trong for...in. configurable: true cho phép xóa/redefine sau này.