apply和call的区别
apply()和call()方法
每个函数对都有两个非继承而来的方法apply()和call(),这两个方法的用途都是用来调用函数(在特定的作用域中),实际上等于设置函数体内的this对象的值。调用函数,实际上就是调用该函数对象的call内部方法。
两者的区别:
apply()方法有两个参数,分别是运行函数的作用域,另一个是参数数组(可以是Array也可以是arguments)。
call()方法的第一个参数和apply()的第一个参数一样,其它参数就是调用函数的参数(相当于把,apply第二个参数的每个元素单列出来)
<script type="text/javascript">
function Monkey(newId,newName){
this.id = newId;
this.name = newName;
}
function Snake(newId,newName){
this.id = newId;
this.name = newName;
}
function eat(str,str1,str2){
console.log(this.name + "吃" + str + "和" + str1+str2);
}
let m = new Monkey(1,"泰山");
let s = new Snake(2,"小可爱");
//引申出接口的概念
//参数1为实力对象,后续参数为eat的参数
eat.call(m,"香蕉","牛奶","、果啤");
eat.call(s,"老鼠","人","、果啤");
eat.apply(m,["香蕉","牛奶","、果啤"]);
eat.apply(s,["老鼠","人","、果啤"]);
function fun(){
let m = new Monkey(1,"泰山");
eat.apply(m,arguments);
}
fun("香蕉","牛奶","、果啤");
</script>
结果:

apply()和call() 真正的用途:
把函数和对象之间进行解耦
即对象和函数之间可以没有关联

浙公网安备 33010602011771号