Called as a function

  • Call context in non-strict mode (thisIs a global object, strictly schemathisforundefined
function myFunction() {
    returnthis; } myFunction(); // Returns the window objectCopy the code

2. Function method calls

  • The calling context is the current object, i.ethisPoint to current object
var calculator = {
    value1: 1,
    value2: 1,
    add: function() {this.result = this.value1 + this.value2; }}; Calculator.add () // call the add method to calculate the result of calculator.result // =>2 // square brackets (attribute access expression) for the attribute access operation calculator["add"] ()Copy the code
  • Nested functions are called as functions, not in strict modethisIs a global object, which in strict mode isundefined
var o = {
    m: function() { var self = this; // Save console.log(this === o); //"true"f(); // Call the nested function f()function f() {
            console.log(this === o);    // "false": this is the global object or 'undefined' console.log(self === o); //"true": self points to the value of the external function this}}}Copy the code

Constructor calls

  • If a function or method call is preceded bynewKeyword, which constitutes the constructor call.
  • The constructor call creates a new empty object and initializes the newly created object to use as its call context.
var o = {
    m: function() {
        return 1;
    }
}
console.log(new o.m() === 1)    // "false"
Copy the code

In the above code, even though the constructor looks like a method call, it still uses the new object out of new as the call context. That is, in the expression new o.m(), the calling context is not O.

Four, indirect call

Call () and apply() methods Call () and apply() are predefined function methods. Two methods can be used to call a function, and the first argument to both methods is the parent object of the function to be called, which is the calling context.

function myFunction(a, b) {
    returna * b; } myObject = myFunction.call(myObject, 10, 2); / / return 20Copy the code
function myFunction(a, b) {
    returna * b; } myArray = [10, 2]; myObject = myFunction.apply(myObject, myArray); / / return 20Copy the code

Tip:

  • call()apply()The difference is in the second argument: Apply passes in an array of arguments, and call is passed in as an argument to call (starting with the second argument)
  • In strict mode, the first argument becomes the value of this when the function is called, even if the argument is not an object.
  • In non-strict modules, if the value of the first argument is null or undefined, it is replaced by a global object.

At the end

Series of articles:

  • JavaScript is new from the past — prototypes and prototype chains
  • JavaScript is old and new — execution environment and scope
  • JavaScript is old and new — scoped chains and closures
  • JavaScript revisits the past — the implementation of call() and apply()