call() apply() bind()作用:1.都可以改变this的指向2.call apply的作用可以直接调用函数,函数立即执行3.call apply的区别在于参数 apply必须传入数据4.bind 只会产生一个函数的副本,不会立即调用函数
// 第一种使用 调用函数
//以下都是一个函数的调用,没有改变this的指向function fn(){conosole.log("hello world")console.log(this)}fn();fn.call();fn.apply();var f1 = fn.bind(); //只会产生一个函数的副本f1()
//第二种指向
//call apply 在不改变this的指向的时候,call传一个普通值即可 apply 必须是一个数组function foo(n,m){console.log(n,m)console.log(this)}foo(10,20);foo.call(null,20,30)foo.call(null,[]20,30)
//改变this的指向
function foo(n,m){var num =this.a +this.b+n+mconsole.log(num)}var a=10;var b=20foo(30,40)foo.call({a:100,b:200},300,400)foo.apply({a:1000,b:2000},[3000,4000])
使用apply借用别的对象的方法
var max =Math.max(10,20,30,40,50,4)var nums=[100,200,300,4000,50]var res =Math.max.apply(123,nums)
使用applyi转换类数组
类数组也叫伪数组,不是一个真正的数组 也就是说不是使用new+Array 创建出来的不能使用数组的方法 pop push但是类数组当中,也有length属性,也有索引值,可以用来循环遍历,也可以存储数据类数组也是一个对象var obj ={1:'aaa',2:"bbb",3:'ccc',4:"nnn",length:4,b:123} //注意 在没添加length之前是一个对象,在添加length之后变成伪数组//类数组存储数据obj.aaa=200;var arr=[];Array.prototype.push.apply(arr,obj)console.log(arr) //只打印length 之前的数据
