在JavaScript中,每个函数都有两个非继承而来的函数apply()和call(),它们的作用呢就是改变函数运行时的上下文。
本质上事改变了函数体内this的指向。
bind()也一样。
function add(x, y) {return x + y;}function test(x, y) {return add.call(this, x, y)}console.log(test(10, 20))
call函数
call函数在调用一个函数的时候,会把该函数的执行对象上下文改为另一个对象
function.call(thisArg,arg1,arg2,...)
如:
function add(a, b) {return a + b;}function test(x, y) {return add.call(this, x, y);}console.log(test(90, 10)); // 100
apply函数
和call一样只是在传参数形式有所差异
function.apply(thisArg,[argsArr])
正如:
function add(a, b) {return a + b;}function test(x, y) {return add.call(this, x, y);}function add1(x,y){return add.apply(this,[x,y])}console.log(test(90, 10)); // 100console.log(add1(9, 10)); // 19
bind函数
bind函数是创建一个新函数,在调用的时候设置this作为提供的值
function add(a, b) {return a + b;}function test(x, y) {const aa = add.bind(this, x, y);return aa();// return add.call(this, x, y);}function add1(x, y) {return add.apply(this, [x, y])}console.log(test(90, 10)); // 100console.log(add1(9, 10)); // 100
call()和apply()在执行后会立即执行前面的函数,而bind()函数不会立即调用,bind 会返回一个新的函数,可以在任何时候调用。
数组最大值和最小值
Math.max.apply(null,arr);Math.min.apply(null,arr);
类数组转为数组
Arrar.prototype.slice.call(arguments)
