Skip to content
youhoc
  • Pages
    • Home
    • Modern App Guidelines
    • Linux
      • Day 1: Linux Distributions & Navigation
      • Day 2: User Management
      • Day 3: File Permission & Ownership
      • Day 4: Package Management
      • Day 5: Services Management
    • Javascript
      • JS The Weird Part
        • Execution Context
        • Types & Operators
        • icon picker
          Objects & Functions
        • Error Handling & Strict Mode
        • Typescript, ES6, Tra
      • Modern JS
        • JS in the Browser
        • Data Storage JSON
        • Modern JS
        • Advanced Objects & Methods
        • Webpack & Babel
        • Async
      • jQuery
        • In-depth Analysis of jQuery
      • React-ready JS
        • Arrow Function
        • Template Literals
        • Logical AND, OR, Ternary, Nullish Operators
        • Destructuring & Rest Operator
        • Array Method
        • Immutability and Spread Operator
        • Promises, Async/Await, Callback
    • PHP
      • gruntJS
      • composer
      • MySQL
    • Docker
      • Container Basics
      • Container Networking
      • Container Image
      • Container Volume & Persistent Data
      • Dockerfile
      • Docker Compose
      • Docker Registry
    • Node.js
      • Installing & Exploring
      • Loading Modules
      • npm - Get Command Input
      • Web Server
        • Express Web Server
        • Template Engine & MVC
      • Authentication
      • 7. Databases
      • 8. Rest API
      • Errors
      • Sequelize
        • Sequelize Transactions: Đảm Bảo Tính Toàn Vẹn Dữ Liệu
        • 7 loại Data Types phổ biến Trong Sequelize
        • Phân Trang (Pagination) Trong Express.js Với Sequelize/MySQL
      • File Upload với Multer, Express.js
      • Hướng dẫn Cơ bản về Rest API
      • Server-Side Validation Với Express-Validator
      • Authentication Trong REST API Với JWT
    • ReactJS
      • React from Andrew
        • Summary from Next
        • 1. Basics
        • 2. React Components
        • 3. Webpack
        • 4. Styling with SCSS
        • 5. React Router
        • 6. React Hook
      • Modern React From The Beginning
        • Intro to JSX
        • Vite Build Tools
        • Basic Component Creation
        • Component State
        • Props & Component Composition
        • useState with Inputs & Form Submission
        • useEffect, useRef & Local Storage
        • Async / Await and Http Request in React
        • React Router: Declarative Mode
        • ContextAPI
        • React Router: Framework Mode
          • File-routing & HTML Layouts
          • Server-side Data Query
          • Links & Navigation
          • Loaders
    • Typescript
      • Type User vs UserProp
    • Payload CMS
    • Authentication

Objects & Functions

Object can contain:
name / value
other objects
functions
Create an object:
// reserve in memory
var person = new Object();

// set properties
person["name"] = "Tony";
person["country"] = "Vietnam";

// access object properties
console.log(person)
console.log(person.name)
console.log(person.country)

var nameProperty = "name";
console.log(person["nameProperty"])

// set other object inside object
person.address = new Object();
person.address.street = "Yen Do";
person.address.city = "Ho Chi Minh";

// access object inside object
console.log(person.address.street);
console.log(person["address"]["street"];
Thường chỉ nên dùng DOT để truy cập giá trị của Object
console.log(person.name)
Chỉ nên dùng STRING ARRAY khi cần truy cập giá trị bằng tên động
var nameProperty = "name";
console.log(person["nameProperty"])
Object Literals
// new Object(), reserve in memory
var person = {};

var Tony = {
name: 'Tony',
country: 'Vietnam',
address: {
street: 'Yen Do',
city: 'Ho Chi Minh'
}
};

// function to call an object
function greet(person) {
console.log('hi ' + person.name)
}

greet(Tony); // 'hi Tony'

// create object on the fly
greet( {name:'Mary',country:'US'} ); // 'hi Mary'
JSON & Object Literals
// object
var objectName = {
name: 'Tony',
country: 'Vietnam',
address: {
street: 'Yen Do',
city: 'Ho Chi Minh'
}
};

// convert to JSON string
console.log( JSON.stringlify(objectName) )
// JSON
{
"name": "Tony",
"country": "Vietnam",
"address": {
"street": "Yen Do",
"city": "Ho Chi Minh"
}
}
// convert string to JSON
var jsonVar = JSON.parse( '{ "street": "Yen Do", "city": "Ho Chi Minh"}' )

Function & Object Literals

Functions are Objects
First-class Functions: everything you can do with other types, you can do with funtion.
Assing them to var, pass around, create on the fly
Function cũng có:
property: name / values
objects
function con
Function có thêm:
invocable (có thể gọi được)
có code bên trong
Function Expression: một đoạn mã trả lại một giá trị
Function Statement: một đoạn mã chỉ thực hiện một hành động (so sánh IF hay in ra log)

By Value & By Reference

MUTATE vs NEW OBJECT

‘this’

Seem like a bug in JS, but this is an unusual scenario:

Arrays

arguments and SPREAD

là những gì bạn truyền vào bên trong một function
SPREAD
Function Overloading
Một cách hay để chia nhỏ function, không truyền quá nhiều arguments
Lưu ý Syntax Parser
Nên tự hết dòng bằng dấu chấm phẩy, vì nếu để JS tự thêm chấm phẩy thì sẽ có nhiều bug khó track
Whitespace: xuống hàng, spacing, tabbing

Immediate Invoking Function

Phong cách viết này rất dễ gặp trong các framework nổi tiếng say này.
ĐỂ TÁCH BIỆT NHỮNG FILE JS CÓ BIẾN RIÊNG, CHẠY ĐỘC LẬP, TRẢ VỀ KẾT QUẢ XONG RỒI BIẾN MẤT
KHÔNG ẢNH HƯỞNG ĐẾN NHỮNG FILE JS TRÊN HAY DƯỚI, không ảnh hưởng đến Global Object
có thể tùy chọn access những biến global nếu thích, nhưng sẽ an toàn
Tình huống kinh điển:

Closures

Ngay cả khi 1 hàm đã chạy xong, thì những biến và hàm bên trong hàm đó vẫn còn hiệu lực
gọi là closure:
image.png
Ngay cả khi greet() đã chạy xong thì các biến và hàm bên trong greet vẫn còn hiệu lực.
Tình huống kinh điển: chắc để tạo ra 1 mớ hàm
Nếu muốn lưu biến i chạy vòng lặp và thu gọn các dòng code:
sử dụng IIFE
sử dụng let trong ES6
Tạo ra factory function
image.png
Closure & Callback
callback là ứng dụng của closure
call(), apply(), bind()
Function Borrowing
Mượn hàm của object này, chạy cho object khác
Function Currying
Copy hàm với một bộ giá trị param chỉ định
Tổng kết:
bind có thể thực hiện với object để thay đổi bối cảnh ‘this’
bind có thể thực hiện với ‘this’ để thay đổi param mặc định (’this’ không đổi)
bind không thực thi, call và apply thực thi

Functional Programming

Code đẹp để tạo ra 1 hàm xử lý mảng
// ví dụ, có 1 mảng, map thành 1 mảng mới với một điều kiện nhất định
var arr1 = [1,2,3];

// ví dụ muốn xử lý mảng rồi tạo ra 1 mảng mới
var arr2 = [];

// đây là cách thường làm
for(var i=0; i < arr1.length; i++) {
// map giá trị của mảng 2 tương ứng với mỗi giá trị của mảng 1...
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.