This is the first article I participated in beginners’ introduction

I. Function (related to function)

Functions have a define-time context, a run-time context, and the notion that context can change

The difference between call and apply

  • Call takes arguments one by one
  • Apply accepts arrays

When the number of parameters passed is uncertain, use apply

Call (obj, parameter 1, parameter 2, parameter 3…) ;

Apply (obj,[parameter 1, parameter 2, parameter 3… );

B: I’m sorry

The bind method is similar to call in that it does not execute immediately after changing the context

let oo = { x:1 } let foo = { getX : function(){ console.log(this.x) } } foo.getX.call(oo); foo.getX.apply(oo); foo.getX.bind(oo)(); Note that the parentheses after bind denote executionCopy the code

Borrow methods from other objects

Var Person1 = function(){this.name = 'Person1 '; } var Person2 = function(){ this.getName = function(){ console.log(this.name); } // console.log(this); // all person1.call (this) in Person2; } Person1 = new Person2(); Person2 = new Person2(); Person2 = new Person2(); person.getName(); // person is an instance of Person2. // Person inherits all the attributes and method getName of Person2Copy the code

Four examples,

1. Find the maximum and minimum values of the array

Math.max(a,b,c...); : Maximum number of numbers * math.min (a,b,c...) : * * Nums does not have Max and min methods, but Math does. Let nums = [100,20,-199,33] let nums = [100,20,-199,33] let maxNum = Math.max.apply(null,nums); let minNum = Math.min.apply(null,nums); console.log(maxNum); // 100 console.log(minNum); // -199 Es6 extension operator console.log(math.max (... nums)); // 100 console.log(Math.min(... nums)) // -199Copy the code