Linh Ngo
Nodejs developer. Working in a tech education company - Techmastervn with a vision to promote STEM and provide valuable as well as affordable IT training to students and young adults
var batman = {
firstName: 'Bruce',
lastName: 'Wayne',
age: 30,
car: {
name: 'Batmobile ',
color: 'Black'
},
driveCar: function () {
console.log('Batman is driving a super car !!!')
},
}// 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
// 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 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 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
// 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 !!!
// 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]
Phương thức riêng của modelS
modelS.__proto__
Object.__proto__
By Linh Ngo