js里apply用法

1、Function.apply,用于构造函数的继承,继承另外一个构建对象的属性与方法

function People(name,age){
    this.name = name;
    this.age = age;
}

function Student(age){
    this.age = age;
    People.apply(this,arguments)
}
var stu = new Student('liujinyu','12');
var peo = new People('liujinyu','12')
console.log( stu)  //{age:"12",name:"liujinyu"}
console.log(peo)   //{name:"liujinyu",age:"12"  }

 

2、用于调用函数,传参。传一个数组进去,形参会逐一匹配数组中的元素。

function peo(name,age){
    console.log(name,age);
}
var arr = [['liu','12'],['jin','13'],['yu','14']];
$.each(arr,function(i,v){
   peo.apply(null,v);
    //peo(v[0],v[1]);   //等同效果
})
//输出结果
//liu 12
//jin 13
//yu 14
posted @ 2014-09-19 19:21  刘金宇  阅读(332)  评论(0编辑  收藏  举报