[JavaScript] this points to best practices

Keywords: PHP Javascript Attribute

1. this, in fact, can be analogous to adults

When it comes to this, our main research in js is this in the function. In javascript, this represents the executing body of the current behavior, while context represents the environment (region) in which the current behavior is executed.

For example, the male god eats at Beilizhu, which means the following

The Godfather -->> the Subject (this)

Eat -->> function

Beilizhu--> Environment

-- > > Explanation: Eating is a function, male god is the main body of the function, and Beilizhu is the execution environment of the current behavior. The main body has no necessary connection with the context, and the main body is only related to the function. It is like a male god eating, in fact, everywhere can eat. The main body of this action is always a male god, and the environment can be changed.

The -->> conclusion: above, it can also be explained that who this refers to has no relation to where the function is defined and executed.

 

2. How to distinguish this in a function

1. To execute a function, first see if there is a'. 'in front of the function name. If there is a'.' then who is in front of it and who is this; if there is no, this is window.

//Example 1
console.log(this);
function eat() {
    console.log(this); //this->window
}
~function() {
    eat(); //this->window
}();

//Example 2
function fn() {
    console.log(this);  
}
var obj = {fn: fn};
fn(); //this->window
obj.fn() //this->obj

//Example 3
function sum() {
    fn();  
}
sum(); //this->window

//Example 4
var oo = {
    sum: function() {
        console.log(this);
        fn();
    }
}
oo.sum(); //First inside the sum function, the first output this is oo; then fn(), this is window

  

2. this in the immediate execution function will always be window

(function() {
    console.log(this); // this->window
})()

 

3. Bind a method to an event of an element, when the event triggers, execute the corresponding method, where this is the current element

function fn() {
    console.log(this);
}
//Example 1
document.getElementById("div1").onclick = fn; //This -> DOM element
//Example 2
document.getElementById("div1").onclick = function() {
    console.log(this); // this->#div
    fn(); // this->window
}

Conclusion: Find out where the function is executed, a little bit, this is before the point; no point, this is window

 

3. Use this to analyze an interview question

var  num = 20;
var obj = {
    num: 30,
    fn: (function(num) {
        this.num *= 3;
        num += 15;
        var num  = 45;
        return function() {
            this.num *= 4;
            num + =20;
            console.log(num);
        }
    })
};
var fn = obj.fn;
fn(); // ->65
obj.fn(); // ->85
console.log(window.num, obj.num) // ->240, 120

 

The above code is described using a stack diagram, as follows: first, the square represents stack memory (function execution environment, context), and the rounded square represents stack memory (used to store strings).

The first step is to form a js execution environment, window scope, first pre-interpret (declare var, declare + define function);

Step 2, code executes from top to bottom, num = 20, obj = reference data type (data exists in heap memory)

The third step, because obj.fn is an immediate execution function, forms a private scope A to execute the function inside FN because the function inside FN returns a function, and the return value is referenced by the external obj.fn. This immediate execution function A scope is not destroyed.

In step 4, the code under the window scope continues to execute.

 

4. this Practice

There is now a requirement to make an accumulator that adds up to 1 for every click.

var oBtn = document.getElementById("btn");
var spanNum = document.getElementById("spanNum");
// Method One
// Define the number that needs to be added as a global variable using the principle of global scope not destroyed
var count = 0;
oBtn.onclikc = function() {
    count++;
    spanNuM.innerText = count;  
}
// Disadvantage: In order to prevent conflicts between global variables in a project, we generally prohibit or reduce the use of global variables

// Method 2
// Form a destroyed private scope to hold the data we need to accumulate
// 1)
(function() {
    var count = 0;
    oBtn.onclick = function() {
        ++count;
        spanNum.innerText = count;
    } 
})
// 2)
oBtn.onclick = (function() {
    var count = 0;
    return function() {
        ++count;
        spanNum.innerText = count;
    }
})
// Both of the above expressions mean the same thing
// Disadvantage: There's a private scope that doesn't destroy, and it takes up a little bit of memory

// Method Three
// Using innerHTML, each click requires that you go to the page to get the latest values, add them up, and put the results in
oBtn.onclick = function() {
    ++spanNum.innerHTML;  
}
// The disadvantage: innerHTML is acquired by the browser. Each time, the memory of the page needs to be converted into a string, then added back, and the browser needs to render the page again when it is added back.

// Method 4
// Store using custom attributes (recommended!)
oBtn.count = 0;
oBtn.onclick = function() {
    spanNum.innerTxt = ++this.count;    
}
//Note that count here is only an attribute of an object, and it is neither a global variable nor a local variable.

  END

Posted by Dlex on Thu, 27 Jun 2019 10:20:37 -0700