js中apply/call/bind

文章类型:Javascript

发布者:hp

发布时间:2023-03-01

一:作用

都是改变this指向,强制绑定在指定的那个对象上

浏览器中=>this指向window对象

函数中=>this指向最后调用对象

构造函数中=>this执行new出来新的对象

箭头函数中=>this是父作用域的this,也就是指向包裹函数的第一个普通函数,声明的时候就确定下来

class中=>指向新创建的类实例

二:用法

1:fn.call(this参数,形参1,形参2...)=>可以 调用函数,接收参数列表,直接执行,如果给 call() 内部传递多个参数,那么第一个默认为 改变 this 的参数,后面为传给函数的参数。

function fn() {
console.log(12)
}

fn.call() // 12

let Dog = {
name: '旺财',
sayName() {
console.log(this.name)
},
eat(food1, food2) {
console.log(this.name + '吃的食物是:' + food1 + ',' + food2)
},
}

let Cat = {
name: '小狗',
}

Dog.sayName.call(Cat) //小狗
Dog.eat.call(Cat, '鱼', '骨头') ////小狗吃的食物是:鱼,骨头

2:fn.apply(this参数,参数的数组)=>接收参数数组,直接执行

Dog.sayName.call(Cat)   //小狗
Dog.eat.call(Cat, ['鱼', '骨头']) ////小狗吃的食物是:鱼,骨头

3:const newFn=fn.bind(this参数,函数参数1,函数参数2...)=>返回待执行函数

会创建一个新的绑定函数,包装了原函数的对象,调用绑定函数会执行包装函数

let fn1 = Dog.eat.bind(Cat, '鱼', '骨头')
fn1()

三:应用场景

1:通过 this 的指向,进行函数方法的继承 .可以进行单个或者多个继承

function Animal() {
this.say = function () {
console.log('我能说话')
}
}
function Fly() {
this.fly = function () {
console.log('我能飞')
}
}

function Cat() {
// Cat 的this指向为cat
Animal.call(this)
//Animal 中的 this 指向也为 cat
Fly.call(this)
//同理 Fly中的 this 也指向了 cat
}
let cat = new Cat()
cat.say()
cat.fly()

2:判断数据类型

function getType(obj){
let type = typeof obj;
if (type !== "object") {
return type;
}
return Object.prototype.toString.call(obj).replace(/^$/, '$1');
}

3:类数组借用方法

var arrayLike = { 
0: 'java',
1: 'script',
length: 2
}
Array.prototype.push.call(arrayLike, 'jack', 'lily');
console.log(typeof arrayLike); // 'object'
console.log(arrayLike);
// {0: "java", 1: "script", 2: "jack", 3: "lily", length: 4}

4:获取数组最大/最小值

  let arr = [13, 6, 10, 11, 16];
const max = Math.max.apply(Math, arr);
const min = Math.min.apply(Math, arr);
console.log(max); // 16
console.log(min); // 6