js中apply和call理解

来源:互联网 发布:自拍神器软件下载 编辑:程序博客网 时间:2024/05/21 17:36

call和apply

用法

    obj.call(thisObj, arg1, arg2, ...);    obj.apply(thisObj, [arg1, arg2, ...]); 

两者作用一致,都是把obj(即this)绑定到thisObj,这时候thisObj具备了obj的属性和
方法。或者说thisObj『继承』了obj的属性和方法。绑定后会立即执行函数。
唯一区别是apply接受的是数组参数,call接受的是连续参数。

案例,dom的nodeList集合有数组的一些基本属性但不是数组,当我们需要使用数组的map方法

    var list = document.querySelectorAll('a');//所有a标签的nodeList    console.log(list.map)// undefined nodeList没有数组的map方法    var test = (item)=>console.log(item)// js lambda表达式    Array.prototype.map.call(list,test)// 打印list的元素    console.log(list.map)//undefined 

这样就可以灵活的使用其他对象的方法而不用继承原型。

参考:http://www.cnblogs.com/52fhy/p/5118877.html