[Front-end Learning] JavaScript keyword this and closure understanding

Links to the original text: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures

1,this

this is not fixed in JavaScript; it changes with the execution environment.

  • In the method, this represents the object to which the method belongs.
  • If used alone, this represents the global object.
  • In a function, this represents the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this represents the element that receives the event.
  • Methods like call() and apply() can reference this to any object.
window.name = 'aa';
var o = {
    name:'bb',
    sayName:function sayName(){
    console.log(this.name);
}
};

function sayName(){
    console.log(name);
}

sayName();
 
o.sayName()

The scope of name is window, and the scope of name in O object is o.

Use this alone

Using this alone, it points to global objects.

In browsers, windows is the global object [object Window]:

var x = this;

In strict mode, if used alone, this also points to global objects.

"use strict";
var x = this;

Use this in functions

In a function, the owner of the function is bound to this by default.

In browsers, windows is the global object [object Window]:

function myFunction() {
  return this;
}

Use this (strict mode) in functions

In strict mode, the function is not bound to this, which is undefined.

"use strict";
function myFunction() {
  return this;
}

this in the event

In the HTML event handle, this points to the HTML element that receives the event:

<button onclick="this.style.display='none'">
After clicking on me, I disappeared.
</button>

Binding in object methods

In the following example, this is the person object, which is the owner of the function:

var person = {
  firstName  : "John",
  lastName   : "Doe",
  id         : 5566,
  myFunction : function() {
    return this;
  }
};

// The output object itself person 
person.myFunction();


var person1 = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

// First Name and lastName in person1 of the output object itself 
person1.fullName ();

Explicit function binding

In JavaScript, functions are objects and objects have methods. apply and call are methods of function objects. These two methods are extremely powerful, allowing you to switch the context in which functions are executed, that is, the objects bound by this.

In the following example, when we call the person1.fullName method with person2 as a parameter, this will point to person2, even if it is the method of person1:

var person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"John",
  lastName: "Doe",
}
person1.fullName.call(person2);  // Return to "John Doe"

Original address

2, closure

 

Closure is a combination of a function and the Lexical Environment in which it is declared.

function init() {
    var name = "Mozilla"; // name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

The alert() statement in displayName() successfully displays the value of the name variable declared in its parent function. The scope used in lexical scope is determined by the location of variables declared in the code. Nested functions can access variables declared outside of them.

Functions in JavaScript form closures. Closures are a combination of functions and the Lexical Environment in which they are created. This environment contains all the local variables that can be accessed when the closure is created.

function makeFunc() {
    var name = "Mozilla";
    function displayName() {
        alert(name);
    }
    return displayName;
}

var myFunc = makeFunc();
myFunc();

MyFunc is a reference to the displayName function instance created when makeFunc is executed, while displayName instance can still access variables in its lexical scope, that is, name. Thus, when myFunc is called, name is still accessible and its value Mozilla is passed to alert.

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

makeAdder(x) function is defined, which accepts a parameter x and returns a new function. The function returned takes a parameter Y and returns the value of x+y.

In essence, makeAdder is a function factory -- he creates a function that adds a specified value to its parameters. In the example above, we used the function factory to create two new functions -- one to sum its parameters and 5, and the other to sum 10.

Add5 and add10 are closures. They share the same function definition, but preserve different lexical environments. In the environment of add5, x is 5. In add10, x is 10.

 

var Counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }   
})();

console.log(Counter.value()); /* logs 0 */
Counter.increment();
Counter.increment();
console.log(Counter.value()); /* logs 2 */
Counter.decrement();
console.log(Counter.value()); /* logs 1 */

A lexical environment is created that is shared by three functions: Counter.increment, Counter.decrement and Counter.value.

The shared environment is created within an immediately executed anonymous function body. This environment contains two private items: a variable named privateCounter and a function named changeBy. Neither of these items is directly accessible outside the anonymous function. It must be accessed through three common functions returned by anonymous functions.

These three common functions are closures that share the same environment.

 

original text

 

 

 

 

Keywords: Javascript Windows

Added by Gregg on Tue, 17 Sep 2019 14:49:27 +0300