call()、apply()、bind() 区别及用法

call()apply()bind()都是Function的prototype中的方法,只有函数才能调用,相应的方法参数如下:

function.call(thisArg, arg1, arg2, ...)
function.apply(thisArg, [argsArray])
function.bind(thisArg[, arg1[, arg2[, ...]]])

主要区别有两个:

1)、call()方法、bind()方法接受的是参数列表,而apply()方法接受的是一个参数数组;

2)、apply()、call()是立即执行函数,bind()是返回对应函数,需要再次调用才能执行。

用法有两种:

一、改变this指针的指向:

1)、改变函数作用域

var name = "小白";
var obj = {
    name: "小红"
};

function sayName() {
    return this.name;
}
console.log(sayName.call(this));   //小白
console.log(sayName.call(obj));    //小红

2)、实现继承

//实现js继承
//父类
function Person(name, height) {
    this.sayInfo = function() {
        return "姓名:" + name + ", 身高:" + height + ", 体重:" + this.weight;
    }
}
//子类
function Chinese(name, height, weight) {
    Person.call(this, name, height);
    this.weight = weight;
    
    this.nation = function() {
        console.log("我是中国人");
    }
}
//子类
function America(name, height, weight) {
    Person.apply(this, [name, height]);
    this.weight = weight;
}

let chiness = new Chinese("成龙", "178cm", "60kg");
console.log(chiness.sayInfo());    //姓名:成龙, 身高:178cm, 体重:60kg
let america = new America("jack", "180cm", "55kg");
console.log(america.sayInfo());    //姓名:jack, 身高:180cm, 体重:55kg

3)、React中使用bind使函数可以获取到props

class MyCircle extends Component {
    constructor(props) {
        super(props)
        this.func = this.func.bind(this)
    }
    func() {
        ...
    }
    ...
}

二、数组操作:

1)、判断对象类型

var arr1 = [];
console.log(Object.prototype.toString.call(arr1)); // [object Array]
console.log(arr1.toString()); // 空
function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]'
}
isArray([1]) // true
isArray({}) // false

2)、找出数组中最大或者最小的元素

var arr2 = [10, 2, 5, 28, 9];
Math.max.apply(Math, arr2); // 28
Math.min.apply(null, arr2) // 2
var arr = [1, 2, 3, 4]

//取最大值
console.log(Math.max.apply(Math, arr)) // 4
console.log(Math.max.call(Math, ...arr)) // 4

//取最小值
console.log(Math.min.apply(Math, arr)) // 1
console.log(Math.min.call(Math, ...arr)) // 1

3)、伪数组转为真正的数组

Array.prototype.slice.apply({0: 1, length: 1}); // [1]
Array.prototype.slice.apply({0: 1, length: 2}); // [1, undefined]

参考文章

JavaScript中call()函数详细用法_甫子陵的博客-CSDN博客_call函数 

apply、call、bind的应用场景 - 简书 

JS中call()和apply() - 简书


call、apply、bind 的区别和使用场景 - 简书

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值