js中call和apply

1、定义:

 apply:方法能劫持另外一个对象的方法,继承另外一个对象的属性.

   如: Function.apply(obj,args),obj:这个对象将代替Function类里this对象

                 args:这个是数组,它将作为参数传给Function。

call:和apply的意思一样,只不过是参数列表不一样. 

   如:Function.call(obj,[param1[,param2[,…[,paramN]]]]),obj:这个对象将代替Function类里this对象

                              params:这个是一个参数列表

2、示例: 

首先, Person.apply(this,arguments)中this指向var student,也就是student窃取了Person方法,用student的参数去执行命名为student的Person方法。在Student与Person参数顺序不一致时用call直接指定对应参数(如Person(age,name)可以用Person.call(this,age,name,grade)将student中参数顺序更正)

3、其他用法

可以将数组转为参数列表;如var max=Math.max.apply(null,array),Array.prototype.push.apply(arr1,arr2)(但性能不如concat)

 

posted @ 2017-08-04 08:42  breadd  阅读(150)  评论(0)    收藏  举报