This is the 28th day since I participated in the August Gwen Challenge.

JavaScript advanced

JavaScript Advanced (2)

JavaScript advanced (three) modular

JavaScript advanced (4) anti-shake

JavaScript advanced (five) throttling

JavaScript advanced (6) inheritance

To start with, we might encounter call, apply, and bind methods in everyday development. Looking at these methods, bind this to the past. It might be a little confusing, but let me take you through these three methods today. Without further ado, let’s go!

call, apply, bind

call

The call() method calls a function with a specified this value and one or more arguments given separately.

Note: The syntax and actions of this method are similar to those of the [apply()] method, except that the call() method accepts a list of arguments, whereas the apply() method accepts an array of arguments.

function student(name, sex) {
    this.name = name;
    this.sex = sex;
}

function cStudent(name, sex) {
    student.call(this, name, sex);
    this.name = 'ZhangSan';
}

console.log(new cStudent('LiSi', 'boy').name);
// ZhangSan

Copy the code

apply

The apply() method calls a function with a given this value and provides arguments in the form of an array (or array-like object).

Note: The call() method works like apply() except that call() takes a list of parameters, while apply() takes an array of parameters.

const numArr = [1.2.3.4.5.6.7.8.9];

const max = Math.max.apply(null, numArr);

console.log(max);
/ / 7

const min = Math.min.apply(undefined, numArr);

console.log(min);
/ / 2

Copy the code

Null or undefined is automatically replaced with a reference to a global object

bind

The bind() method creates a new function, and when bind() is called, this of the new function is specified as the first argument to bind(), and the remaining arguments will be used as arguments to the new function.

const count = {
    x: 42,
    y: 24,
    add: function() {
        return this.x + this.y; }};const add = count.add;
console.log(add());
// Nan

const cAdd = add.bind(count);
console.log(cAdd());
/ / 66
Copy the code

END~~~