call、apply和bind方法的学习

bind、call、apply都是用来指定一个函数内部的this的值, 先看看bind、call、apply的用法
 

var year = 2021
function getDate(month, day) {
  return this.year + '-' + month + '-' + day
}

let obj = {year: 2023}
getDate.call(null, 3, 8)    //2022-3-8
getDate.call(obj, 3, 8)     //2022-3-8
getDate.apply(obj, [6, 8])  //2022-6-8
getDate.bind(obj)(3, 8)     //2022-3-8

1. call() 方法

call()方法接受的语法和作用与apply()方法类似,只有一个区别就是call()接受的是一个参数列表,而apply()方法接受的是一个包含多个参数的数组。

二者都是函数对象Function的方法,且第一个参数都是要绑定对象的上下文
例如:

let obj = {
    a: 1,
    get: function(){
        return 2
    }
}
let g = obj.get
g.call({},1,2,3)
g.apply({},[1,2,3])
  • call方法调用父构造函数
    function Product(name, price){
        this.name = name;
        this.food = food;
    }
    
    // 调用父构造函数的call方法来实现继承
    function Food(name, price){
        Product.call(this.name, toy);
        this.category = 'food';
    }
    
    function Toy(name, price){
        Product.call(this, name, price);
        this.category = 'toy';
    }
    
    var cheese = new Food('feta', 5);
    var fun = new Toy('robot', 40);
    
  • call方法调用匿名函数
    var animals = [
        {species: 'Lion', name: 'King'},
        {species: 'Whale', name: 'Fail'}
    ];
    
    for(var i = 0; i < animals.length; i++){
        (function(i){
            this.print = function(){
                console.log('#' + i + ' ' + this.species + ': ' + this.name);
            }
            this.print();
        }).call(animals[i], i); //call调用匿名函数
    }
    
  • call方法调用函数并且指定上下文的this
    var obj = {
        animal: 'cats', sleepDuration: '12 and 16 hours'
    };
    
    function greet(){
        var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
        console.log(reply);
    }
    
    greet.call(obj);  //"cats typically sleep between 12 and 16 hours"
    
  • call方法调用函数并且不指定第一个参数(argument)

没有传递第一个参数,this的值将被绑定为全局对象。

var sData = 'marshall';

function display(){
    console.log("sData's value is %s",this.sData);
}

display.call();  // sData value is marshall

但是在严格模式下,this 的值将会是undefined

var sData = 'marshall';

function display(){
    console.log("sData's value is %s",this.sData);
}

display.call();  // Cannot read the property of 'sData' of undefined

2. apply() 方法
使用 apply, 我们可以只写一次这个方法然后在另一个对象中继承它,而不用在新对象中重复写该方法。

apply 与 call() 非常相似,不同之处在于提供参数的方式。apply 使用参数数组而不是一组参数列表。apply 可以使用数组字面量(array literal),如 fun.apply(this, [‘eat’, ‘bananas’]),或数组对象, 如 fun.apply(this, new Array(‘eat’, ‘bananas’))。

  • apply方法调用一个具有给定this值的函数,以及以一个数组的形式提供参数。
    var array = ['marshall','eminem'];
    var elements = [0,1,2];
    array.push.apply(array,elements);
    console.log(array);  //['marshall','eminem',0,1,2]
    
  • 使用apply和内置函数

对于一些需要写循环以遍历数组各项的需求,我们可以用apply完成以避免循环。

//找出数组中最大值和最小值
var numbers = [5, 6, 2, 3, 7];
//使用Math.min和Math.max以及apply函数时的代码
var max = Math.max.apply(null, numbers);
var min = Math.min.apply(null, numbers);

上边这种调用apply的方法,有超出JavaScript引擎参数长度上限的风险。
如果我们的参数数组非常大,推荐使用下边这种混合策略:将数组切块后循环传入目标方法

function minOfArray(arr) {
    var min = Infinity;
    var QUANTUM = 32768;
  
    for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
      var submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));
      min = Math.min(submin, min);
    }
  
    return min;
  }
  
  var min = minOfArray([5, 6, 2, 3, 7]);

 apply与call的实现

// call和apply实现方式类似,只是传参的区别
// 基本思想是把fn.call(obj,args)中的fn赋值为obj的属性,然后调用obj.fn即可实现fn中this指向的改变
Function.prototype.myCall = function(context = window){ //myCall函数的参数,没有传参默认是指向window
  context.fn = this //为对象添加方法(this指向调用myCall的函数)
  let args = [...arguments].slice(1) // 剩余的参数
  let res = context.fn(...args)  // 调用该方法,该方法this指向context
  delete context.fn //删除添加的方法
  return res
}

Function.prototype.myApply = function(context = window){ //myCall函数的参数,没有传参默认是指向window
  context.fn = this //为对象添加方法(this指向调用myCall的函数)
  let res
  if(arguments[1]){ //判断是否有第二个参数
    res = context.fn(...arguments[1])// 调用该方法,该方法this指向context
  }else{
    res = context.fn()// 调用该方法,该方法this指向context
  }
  delete context.fn //删除添加的方法
  return res
}

// 验证
function sayName(name= 'wwx',age= 18){
  this.name = name
  this.age = age
  console.log(this.name)
  return this.age
}
var obj = {
  name : 'zcf',
  age:24
}
var age = sayName.myCall(obj,"wxxka",19) // 19
var age1 = sayName.myApply(obj,["wwxSSS",20]) //20

3. bind 简介
bind()函数会创建一个新的绑定函数,这个绑定函数包装了原函数的对象。调用绑定函数通常会执行包装函数。
绑定函数内部属性:

包装的函数对象
在调用包装函数时始终作为this传递的值
在对包装函数做任何调用时都会优先用列表元素填充参数列表。
而原函数 retrieveX 中的 this 并没有被改变,依旧指向全局对象 window。
 

this.x = 9; //this指向全局的window对象
var module = {
    x: 81,
    getX: function(){return this.x;}
};

console.log(module.getX()); //81

var retrieveX = module.getX;
console.log(retrieveX()); //9,因为函数是在全局作用域中调用的

// 创建一个新函数,把this绑定到module对象
// 不要将全局变量 x 与 module 的属性 x 混淆
var boundGetX = retrieveX.bind(module);
console.log(boundGetX()); //81

bind传递参数问题:
在通过bind改变this指向的时候所传入的参数会拼接在调用返回函数所传参数之前,多余参数不起作用。

var newShowName = showName.bind(newThis, 'hello');
//在通过bind改变this指向的时候只传了“hello”一个参数,
//在调用newShowName这个返回参数的时候,bind传参拼接在其前
newShowName('world'); //输出:newThis hello world

var newShowName = showName.bind(newThis, 'hello');
//在通过bind改变this指向的时候只传了“hello”一个参数,
//在调用newShowName这个返回参数的时候,bind传参拼接在其前,
//这时newShowName的参数为“hello”,“a”,“world”
//而该函数只需要两个参数,则第三个参数被忽略
 newShowName('a','world'); //输出:newThis hello a

bind传入的参数和newShowName方法传入的参数会拼接在一起,一齐传给showName方法。

bind无法改变构造函数的this指向

var name = 'window';
var newThis = { name: 'newThis' };
function showName(info1, info2) {
    console.log(this.name, info1, info2);
}
showName('a', 'b'); //输出:window a b

// 通过bind改变this指向
var newShowName = showName.bind(newThis, 'hello','1','2');
newShowName('a','world'); //输出:newThis hello world

console.log(new newShowName().constructor); //输出:showName函数体

. bind的实现

通过apply模拟bind源码实现:

Function.prototype.myBind = function(context = window){
  let fn = this // 调用bind的函数
  let args = [...arguments].slice(1) // myBind的参数
  let bind = function(){
    let args1 = [...arguments].slice() // bind的参数
    return fn.apply(context,args.concat(args1))
  }
return bind
}

// 测试
var obj = {
  name : 'zcf',
  age:24
}
function sayName(name= 'wwx',age= 18){
  this.name = name
  this.age = age
  console.log(this.name)
  return this.age
}
var mb = sayName.myBind(obj)
mb() // obj = {name:"wwx",age:18}
mb("acfwwx",1819) // obj = {name:"acfwwx",age:1819}
};

 什么情况下用apply,什么情况下用call
在给对象参数的情况下:

如果参数的形式是数组的时候,比如apply示例里面传递了参数arguments,这个参数是数组类型,并且在调用Person的时候参数的列表是对应一致的(也就是Person和Student的参数列表前两位是一致的) 就可以采用 apply。

如果我的Person的参数列表是这样的(age,name),而Student的参数列表是(name,age,grade),这样就可以用call来实现了,也就是直接指定参数列表对应值的位置(Person.call(this,age,name,grade));

 call和apply 应用场景

a. 函数之间的相互调用

b. 构造函数之间的调用

c. 多重继承

使用多个call 或者apply 即可。

d. 类数组共用数组方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值