Object ใน JavaScript การสร้าง Object

1. Object Literals
การกำหนดค่าโดยตรง

let empty = {};                          // An object with no properties
let point = { x: 0, y: 0 };              // Two numeric properties
let p2 = { x: point.x, y: point.y+1 };   // More complex values
let book = {
    "main title": "JavaScript",          // These property names include spaces,
    "sub-title": "The Definitive Guide", // and hyphens, so use string literals.
    for: "all audiences",                // for is reserved, but no quotes.
    author: {                            // The value of this property is
        firstname: "David",              // itself an object.
        surname: "Flanagan"
    }
};


2. ใช้คำสั่ง new

let o = new Object();  // Create an empty object: same as {}. 
let a = new Array();   // Create an empty array: same as [].
let d = new Date();    // Create a Date object representing the current time
let r = new Map();     // Create a Map object for key/value mapping

3. ใช้ Prototype

Object เกือบทั้งหมดจะถูกผูกไว้กับ object ตัวที่สองที่เรียกว่า prototype และ Object จะสืบทอด property และ method มาจาก prototype

Object ที่สร้างด้วย object literal จะมี prototype เดียวกันทั้งหมด เราสามารถเรียก prototype นี้มาดูได้ด้วยคำสั่ง Object.prototype 
Object ที่ถูกสร้างด้วย constructor จะได้ prototype มาจาก constructor function. ดังนั้น 
  • object ที่สร้างด้วย new Object(); ก็จะมี prototype เป็น Object.prototype 
  • object ที่สร้างด้วย new Array(); ก็จะมี prototype เป็น Array.prototype
  • object ที่สร้างด้วย new Date(); ก็จะมี prototype เป็น Date.prototype 
Object เกือบทั้งหมดใน JavaScript จะมี prototype แต่มีเพียงไม่กี่ Object ที่จะมี property prototype.
Property prototype นี้จะถูกให้เป็น prototype ของ Object อื่นๆ

Object.prototype เป็นหนึ่งใน object ไม่กี่ตัวที่ไม่มี prototype ส่วน object ที่เป็น prototype อื่นๆ ตัวมันเองจะมี prototype เป็น Object.prototype 

เช่น Date.prototype ก็จะมี prototype เป็น Object.prototype ดังนั้นคำสั่ง let d = new Date(); ก็จะทำให้ d มี prototype chain ดังรูป 

Object.create สามารถใช้สร้าง object และกำหนด prototype ได้ดังนี้

let o1 = Object.create({x: 1, y: 2});     // o1 inherits properties x and y.
o1.x + o1.y                               // => 3
let o2 = Object.create(null);             // o2 inherits no props or methods.
let o3 = Object.create(Object.prototype); // o3 is like {} or new Object().


Object.create สามารถใช้ป้องกันการถูกเขียนทับได้ดังโค้ดด้านล่าง หาก library เขียนทับ x จะกลายเป็นการสร้าง property ใหม่ให้ object ลูกแทน

let o = { x: "don't change this value" };
library.function(Object.create(o));  // Guard against accidental modifications


Comments

Popular posts from this blog

15.8.4 การวาดลงบน cavas

15.8.3 Graphics Attributes

15.8.1 path กับ polygon