【JavaScript】- The difference and usage of call(), apply(), bind()

method borrowing pattern

Also called context mode, divided into apply and call, bind

Similarities between the three:

1, are used to change the point of the this object of the function.

2. The first parameter is the object pointed to by this.

3. You can use subsequent parameters to pass parameters.

1.call:

The call method can call a function, and can specify the thispointer to this function

After the call method, the parameter list is passed in, and the parameters can be of any type. If no parameters are passed, or the first parameter is nullor nudefined,this they all point towindow

These methods can be found in the prototype prototype

const RichWumon = {
    name: "富婆",
    say: function () {
        console.log(this.name, " 我要重金求子");
    }
}

const obj = {
    name: "屌丝"
}

RichWumon.say();			// 富婆
RichWumon.say.call(obj);	// 屌丝

// fn.call(你想谁作为this变量,参数列表)
// call可以改变方法中this的指向,会以你调用call方法时传递的变量做为方法中的this

Call details:

non-strict mode

If no parameter is passed, or the first parameter is null or undefined, this all points to window

   let fn = function(a,b){
        console.log(this,a,b);
    }
    let obj = {name:"obj"};
    fn.call(obj,1,2);    // this:obj    a:1         b:2
    fn.call(1,2);        // this:1      a:2         b:undefined
    fn.call();           // this:window a:undefined b:undefined
    fn.call(null);       // this=window a=undefined b=undefined
    fn.call(undefined);  // this=window a=undefined b=undefined

strict mode


Who is the first parameter, who this points to, including null and undefined, if the parameter this is not passed, it is undefined

    "use strict"
    let fn = function(a,b){
        console.log(this,a,b);
    }
    let obj = {name:"obj"};
    fn.call(obj,1,2);   // this:obj        a:1          b:2
    fn.call(1,2);       // this:1          a:2          b=undefined
    fn.call();          // this:undefined  a:undefined  b:undefined
    fn.call(null);      // this:null       a:undefined  b:undefined
    fn.call(undefined); // this:undefined  a:undefined  b:undefined

call application:

// 将伪数组转成数组
let divs = document.querySelectorAll('div'); // 伪数组
// let divs = document.body.children;
console.log(divs);

function change(nodelist) {
    console.log(Object.prototype.toString.call(nodelist));
    return Array.prototype.slice.call(nodelist);

}

// 定义一个伪数组:看起来像数组,但是并没有数组的api,本质上是一个对象
    let arr = {
      0: 1,
      1: 10,
      2: 200,
      length: 3
    }
// 第一个参数是this,后面的是参数列表
    let data = [50, 60, 70, 80, 90];
    [].push.call(arr, ...data)
    console.log(arr)	
/* 输出的是 
Object
0: 1
1: 10
2: 200
3: 50
4: 60
5: 70
6: 80
7: 90
length: 8		// arr[arr.length++] = 50
*/

2.apply:

That is, the apply()method accepts an array with multiple parameters . The call()method accepts a list of several parameters

You can use apply to modify the code of the call just now

apply() has only two parameters , the first is an object and the second is an array.

const RichWumon = {
    name: "富婆",
    say: function () {
        console.log(this.name, " 我要重金求子");
    }
}

const obj = {
    name: "屌丝"
}

RichWumon.say();			// 富婆
RichWumon.say.apply(obj);	// 屌丝

apply : basically the same as call, the only difference is the way of passing parameters

apply puts the parameters that need to be passed to fn into an array (or class array) and passes it in. Although it writes an array, it is also equivalent to passing fn one by one.

applyApply:

// 简化log方法
function log() {
    // 不需要改变this
    console.log.apply(console, arguments);
}
​
​
var obj = {};
function foo(a, b, c) {
      console.log(a);
}
foo.apply(obj, [1, 2, 3])   //打印结果: 2;
//第一个参数是函数的对象,第二个参数是由函数的参数组成的数组
​
// 求数组中的最大值
var arr = [1, 66, 3, 99, 50];
var max = Math.max.apply(arr, arr);//第一个arr表示让arr借用max这个方法,第二个arr表示传给max的数据
console.log(max);       // 99
//apply()所执行的操作:1.执行Math.max(1,2,3,5,4) 2.把内部的this改成arr

3.bind method:

The bind() method creates a new function that can be bound to the thispointer of the new function

The difference between the bind() method and the first two is that the bind() method will return the function whose execution context has been changed without executing it immediately, while the first two directly execute the function. Its parameters are the same as call()

var name = '张三';
function Fn(){
    this.age = 1;
    
    console.log(this.name + this.age);
}

Fn();			// 张三 1

// 返回值:新的函数
// 参数:新函数的this指向,当绑定了新函数的this指向后,无论使用何种调用模式,this都不会改变。
let obj = {
    name:'小强',
}
const newFn = Fn.bind(obj);
newFn();		// 小强 1

 application:

function f() {
  console.log("看我怎么被调用");
  console.log(this) //指向this
}
var obj = {name:'jack'};
f.call(obj) //直接调用函数
// f.bind(obj);    bind()不能调用函数
var g = f.bind(obj); 	// bind()改过this后,不执行函数,会返回一个绑定新this的函数
g();  //此时才调用函数

Guess you like

Origin blog.csdn.net/m0_55960697/article/details/124026341