Objects & Prototype

Objects trong JavaScript

  • Tập hợp dữ liệu. Mỗi phần tử (item) là 1 cặp name-value
  • Item có thể là thuộc tính (property) hoặc phương thức (method)
var batman = {
  firstName: 'Bruce',
  lastName: 'Wayne',
  age: 30,
  car: {
    name: 'Batmobile ',
    color: 'Black'
  },
  driveCar: function () {
    console.log('Batman is driving a super car !!!')
  }, 
}

Dùng `.`

Dùng `[ ]`

Truy xuất dữ liệu trong Objects

// Sử dụng `.` để truy cập dữ liệu
// Với đối tượng batman 

console.log(batman.firstName) // Bruce
console.log(batman.lastName)  // Wayne

// Chi dùng `,` để truy cập 
// phương thức của objects

console.log(batman.driveCar()) 
// 'Batman is driving a super car!!!'
// Sử dụng `[...]` để truy cập dữ liệu

// Bên trong [...] phải là 1 chuỗi

console.log(batman["firstName"]) // Bruce
console.log(batman["lastName"])  // Wayne

Truy xuất dữ liệu trong Objects

    // Có thể truy vấn thuộc tính qua 1 biến, biến này lưu tên thuộc tính theo dạng chuỗi
    
    let obj = {'product_name': 'IPhone'}
    
    console.log(obj.product_name); // IPhone
    console.log(obj['product_name']); // IPhone
    
    let name2 = 'product_id';
    // dùng '.' thì name2 đc hiểu trực tiếp là tên thực của thuộc tính
    
    obj.name2 = 'Samsung'; 
    // dùng [] thì truyền vào giá trị của biến name2 là 'product_id'
    obj[name2] = 'HTC'; 
    
    console.log(obj);
    // { product_name: 'IPhone', name2: 'Samsung', product_id: 'HTC' }
    

Tạo Objects - Object Literals

        // Tạo 1 đối tượng chứa thông tin phim
        
        var kingsMan = {
          title: 'Kingsman: The Secret Service',
          genre: 'Action',
          year: 2014
        } 
        
        
        var myDog = {
          name: 'Bi',
          run: function () {
            console.log('Bi is running')
          },
          bark: function () {
            console.log('Woof Woof')
          }
        }

Tạo Objects - Object Literals

        // Tạo 2 đối tượng kingsMan & myDog
        
        // .......

        module.exports = {
          kingsMan: kingsMan,
          myDog: myDog
        }
        // new ES6 Object literals shortcut
        module.exports = { kingsMan, myDog }
        

Cách viết tắt trong ES6 

Constructor Function

    // Sử dụng hàm khởi tạo - tạo nhiều đối tượng
    
    function Car(name, brand) {
      this.name = name
      this.brand = brand
    }
    var innova = new Car('Toyota Innova', 'Toyota')
    console.log(innova);
    
    // Thêm phương thức 
    // Prototype đc chia sẻ cho tất cả đối tượng tạo từ hàm khởi tạo
    Car.prototype.run = function () {
      console.log(this.name + ' is running !!!');
    }
    
    var modelS = new Car('Tesla Model S', 'Tesla')
    console.log(modelS);
    innova.run(); // Toyota Innova is running !!!
    modelS.run(); // Tesla Model S is running !!!

Prototype là gì? 

  • Prototype là đối tượng trong JS (prototype object)
  • Cách JS objects kế thừa nhau
  • JS không có thuần OOP mà theo cơ chế Prototypal Inheritance 

Prototype Chain


    

    // Xem prototype object qua thuộc tính `__proto__`
    console.log(innova.__proto__); // Car { run: [Function] }
    console.log(innova.__proto__ === modelS.__proto__); // true




    // Nhờ có prototype chain, innova & modelS có thể sử dụng
    // phương thức của Object
    console.log(modelS.hasOwnProperty('name')); // true
    console.log(modelS.hasOwnProperty('run')); // false
    console.log(modelS.toString()); // [object Object]
    

Prototype Chain

Phương thức riêng của modelS 

modelS.__proto__ 

Object.__proto__ 

Objects & Prototype

By Linh Ngo

Objects & Prototype

  • 109