closure javascript

tipjs,scope,global

Example closure javascript

class Example {
  constructor() {
    var _private = '';
    _private = 'private';
    this.getName = function() {return _private}
  }
}
var ex = new Example();
console.log(ex.getName()); // private
console.log(ex._private); // undefined

Lợi thế:

 Không có xung đột đặt tên 

 Không thể truy cập và sửa đổi bên ngoài 

Nhược điểm:

Logic của constructer trở nên phức tạp. 

Hàm tạo chỉ nên thực hiện khởi tạo đối tượng.

Bây giờ để thực hiện các biến riêng tư, nó phải bao gồm việc thực hiện một số phương thức và tổ chức code không rõ ràng. 

Có thể bạn đã miss một số snippets code

Await in a for loop

How to Await in a for loop

Copy a string to the clipboard

Copy a string to the clipboard. Only works as a result of user action (i.e. inside a click event listener).

Sử dụng reduce và concat làm phẳng một array

Array.reduce() và Array.concat() có thể giúp chúng ta làm phẳng một Array như:

serialize Form

Sử dụng formdata constructor để convert form, FormData, array.from(). Kết hợp window.encodeURIComponent() để encode từng value trong form.

Ajax, call jQuery POST to node.js expressjs

Ajax, call jQuery POST to node.js expressjs