Application of closures

Closures are functions that have access to variables in the scope of another function. A function that reads variables inside other functions

0. Encapsulate private variables

function Person0() {
    this._attackVolume = 100;
}
Person0.prototype = {
    / * *... * * /
};
var p0 = new Person0(); console.log(p0._attackVolume); / / 100

// Factory method
function Person1() {
    var _attackVolume = 100;
    return {
        attack() {
            console.log('attack ' + _attackVolume);
            _attackVolume++
        }
    };
}
var p1 = new Person1(); console.log(p1._attackVolume); // undefined
p1.attack() // attack 101
p1.attack() // attack 100
Copy the code

1. Store variables (cache)

function getListDataManager() {
    let localData = null;
    return {
        getData() {
            if (localData) {
                return Promise.resolve(localData); // Returns the stored result
            }
            return fetch('xxxx').then(data= > localData = data.json()); // Real data request}}; }Copy the code

2. The realization of anti-shake throttling function

Refer to the previous article: Parsing several JS handwriting functions (call, anti-shake throttling)

5 scenarios for this

0. Call the function directly

function myfunc() {
    console.log(this)
}
myfunc(); // This is window, strictly undefined
Copy the code

Comma-expression cases:

var obj = {
    show: function () {
        console.log('this:'.this); }}; (0, obj.show)(); // window
Var re = function () {console.lo... }; re();
Copy the code

1. When a function is called by someone else

function myfunc() {
    console.log(this)}var a = {
    myfunc: myfunc
};
a.myfunc(); // This is the object A
Copy the code

The case of a direct call in the form of a call:

function run() {
    console.log(this);
}
var obj = {
    test: function () {
        run()
    }
}
obj.test() // This is window
Copy the code

Whoever calls this is the same:

var obj = {
    sub: {
        show: function () {
            console.log('this:'.this); }}}; obj.sub.show()// This is the object sub
Copy the code

2. New When creating the instance

function Person(name) {
    this.name = name;
    console.log(this);
}

var p = new Person('name'); // p

var obj = {
    show: function () {
        console.log('this:'.this); }};var newobj = new obj.show(); // newobj
Copy the code

New > bind > call

var obj = {
    show: function () {
        console.log('\nthis:\n\n'.this); }}; obj.show();// obj
(obj.show.bind(obj))(); // obj
var newobj = new (obj.show.bind(obj))(); // newobj
Copy the code

3. apply, call, bind

Generally, bind is superior to call/apply. (Many call parameters, few apply parameters)

function getColor(color) {
    this.color = color;
    console.log(this);
}
function Car(name, color) {
    this.name = name; // This refers to instance CAR
    console.log(this)
    getColor.call(this, color); // This is changed from getColor to car
}
var car = new Car('truck'.'green');
Copy the code

Arrow function

Does not have its own this and cannot be called by the new keyword

var a = {
    myfunc: function () {
        setTimeout(() = > {
            console.log(this);
        }, 0)},myfunc2: function () {
        setTimeout(function() {
            console.log(this);
        }, 0)}}; a.myfunc();/ / this is a
a.myfunc2(); / / this is setTimeout
Copy the code

5. Comprehensive application

var obj = {
    show: function () {
        console.log('this:'.this); }};var elem = document.getElementById('xxx');
elem.addEventListener('click', obj.show); // is passed to the click event, which is executed as a direct call, with this referring to the window
elem.addEventListener('click', obj.show.bind(obj)); // explicitly bound to obj, this refers to obj
elem.addEventListener('click'.function () {
    obj.show(); // The execution is called. This refers to obj
});
Copy the code

scope

for (var i = 0; i < 10; i++) {
    console.log(i); // 0 1 2.... 9
}
for (var i = 0; i < 10; i++) {
    setTimeout(function () { // the main stack for is finished, and I is 10
        console.log(i); / / 10
    }, 0);
}
for (var i = 0; i < 10; i++) {
    (function (i) { // Separate 10 scoped blocks
        setTimeout(function () {
            console.log(i); // 0 1 2 3.... 9
        }, 0)
    })(i);
}
for (let i = 0; i < 10; i++) {
    console.log(i); // 0 1 2 3.... 9
}
Copy the code

Affected by JS variable promotion:

var person = 1;
function showPerson() {
    console.log(person); // If there is no person defined by var then the output is 1
    var person = 2; Person in the showPerson scope is pre-declared initialized and assigned undefind
}
showPerson(); // undefined
Copy the code

Affected by JS function promotion:

var person = 1;
function showPerson() {
    console.log(person);
    var person = 2; // Defining this person anywhere in the function scope does not affect the result
    function person() {}// Function promotion: pre-declare initialization and assign the entire function content
}
showPerson(); // function person() { }
Copy the code

object-oriented

function Person() {
    this.name = 1;
}
Person.prototype = {
    name: 2.show: function () {
        console.log('name is:'.this.name); }};var person = new Person();
person.show(); // name is: 1
Person.prototype.show(); // name is: 2

Person.prototype.show = function () {
    console.log('new show');
};
person.show(); // new show
Copy the code