改变this指向[call、apply、bind]
作用: call、apply都是改变this的作用域,在指定的作用域下进行函数调用;如果某个对象没有某种功能(也就是没有某个方法),而其他对象有,则可以通过call、apply方法实现方法的复用,下面具体讲解复用模式
-
传参定义
- call的参数的顺序依次为this的值,函数接收的参数,
- apply方法接受一个包含多个参数的数组;
- bind的传参与call一样,但是他与call、apply不同的是,需要再执行一次
-
call、apply、bind方法使用场景-方法复用
const person1= { name: 'xiaoMing', playBasketball:function(age,other){ console.log(`${age}的${this.name}会打篮球&${other}`); } } const person2= { name: 'xiaoHong', playPaint:function(age,other){ console.log(`${age}的${this.name}会绘画${other}`); } } person1.playBasketball.call(person2,12,'足球')//"12的xiaoHong会打篮球&足球" person1.playBasketball.apply(person2,[12,'足球'])//"12的xiaoHong会打篮球&足球" person1.playBasketball.bind(person2,12,'足球')()//"12的xiaoHong会打篮球&足球"
以上的示例中小明会打篮球,小红会绘画,但是使用了call方法后小红也会打篮球了,这就是方法复用
-
call、apply方法使用场景2-伪数组转数组
var eleRadios = document.querySelectorAll('input[type="radio"]'); [].slice.call(eleRadios).forEach(function (radio) { radio.addEventListener('click', function () { // 略 }); });
此例中eleRadios是一个NodeList结构,不能进行循环,因此使用[].slice.call进行把eleRadios转换成数组类型,之后进行foreach循环
-
call、apply方法使用场景-继承
function Animal(name) { this.name = name; this.showName = function () { console.log(this.name); } } function Cat(name) { Animal.call(this, name); } var cat = new Cat('Cat'); cat.showName(); //"Cat"
-
call、apply方法使用场景-数组追加
var array1 = [1 , 2 , 3, 5]; var array2 = ["xie" , "li" , "qun" , "tsrot"]; Array.prototype.push.apply(array1, array2); console.log(array1);//[1, 2, 3, 5, "xie", "li", "qun", "tsrot"]
-
call、apply方法使用场景-获取数组中的最大值和最小值
var num = [1,3,5,7,2,-10,11]; var maxNum = Math.max.apply(Math, num); var minNum = Math.min.apply(Math, num); console.log(maxNum); //11 console.log(minNum); //-10
牛客中题目
-
var p1 = { name:'小明', age:'12', action:function(where,doing){ console.log(this.age + '岁的'+this.name + '在' + where + doing); } } var p2 = { name:'小红', age:'15' } console.log(p1.action.call(p2,'操场上','运动'))//
备注:第一次新建:2020-11-06