js中Bind和call、apply函数的运用!(详解js中的This对象)
<script>
call:实现功能 1:改变当前的this对象 2:可以去借用其他类的方法 fn.call(对象,参数1,参数2)
//call用法1
//继承的实质就是抽取重复的代码
//父类
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
//子类
![](https://img2020.cnblogs.com/blog/1647475/202004/1647475-20200418111249859-887501720.png)
function Student(name,age,sex,score){
Person.call(this,name,age,sex); //Person.call(), person调用call方法 相当于call方法中的this就是Person js中本来不存在继承 通过这种方式来实现继承 改变this来达到赋值
this.score = score;
}
//call的用法2
![](https://img2020.cnblogs.com/blog/1647475/202004/1647475-20200418111249859-887501720.png)
![](https://img2020.cnblogs.com/blog/1647475/202004/1647475-20200418111134910-1652492083.png)
apply:实现功能 1:改变当前的this对象 2:传递的参数为数组将数组中的每一值展开传递给函数 fn.apply(对象,【】)
常用的场景:就是把数值中的值展开传递给函数去调用
实例1:
![](https://img2020.cnblogs.com/blog/1647475/202004/1647475-20200418113122249-1736070168.png)
实例2
(说白了就是因为Math是一个工具类!个人理解 )
bind:实现功能 1:改变当前的this对象 (与其他的两个不同的是 bind不会去调用方法,只实现改变this对象)
var obj = {name:'zs', fun:function(){setInterval(function(){}.bind(this),1000)}}
</script>
坚持