MongoDB Shell (JavaScript REPL) รองรับการสร้าง Aliases/Shortcuts ผ่าน Object.defineProperty() บน Global Object (this) เพื่อเข้าถึง Function หรือ Value ได้สะดวก
ไวยากรณ์
Object.defineProperty(this, 'yourFunctionName', {
get: function() {
// statements
return value;
},
enumerable: true,
configurable: true
});
// กำหนด Alias ด้วย var
var anyAliasName = yourFunctionName;
ตัวอย่าง: สร้าง Function แสดงข้อความ แล้วตั้ง Alias
> Object.defineProperty(this, 'displayMessageDemo', {
get: function() {
return "Hello MongoDB";
},
enumerable: true,
configurable: true
});
กำหนด Alias
> var myMessage = displayMessageDemo;
ใช้งาน Alias
> myMessage; "Hello MongoDB"
รายละเอียด Property Descriptor
| Property | ค่า | ความหมาย |
|---|---|---|
get | Function | Getter Function เรียกเมื่อ Access Property |
enumerable | true | แสดงใน for...in loop และ Object.keys() |
configurable | true | ลบ/แก้ไข Property ได้ (delete, defineProperty อีกครั้ง) |
set | Function (Optional) | Setter Function เรียกเมื่อ Assign ค่า |