Function.apply:
Function.apply(obj,args)方法能接收两个参数,
obj:这个对象将代替Function类里this对象,
args:这个是数组,它将作为参数传给Function(args-->arguments).
obj:这个对象将代替Function类里this对象,
args:这个是数组,它将作为参数传给Function(args-->arguments).
Function.call:
Function.call(obj,[param1[,param2[,…[,paramN]]]]),
obj:这个对象将代替Function类里this对象,
params:这个是一个参数列表.
obj:这个对象将代替Function类里this对象,
params:这个是一个参数列表.
call和apply一样,只是参数列表不同而已.
Person类:
function Person(name,age) { this.name = name; this.age = age; }
Student类:
function Student(name,age,height) { Person.apply(this,arguments); //Person.call(this,name,age,height); //call方法的传参方式; this.height = height; }
实例化:
var student = new Student("chams",22,"173");
测试:
console.log("name:" + student.name + " age:" + student.age + " height:" + student.height);
Student类中并没有name和age属性,但是通过apply和call的继承,使Student类继承了Person类中的成员方法.
有关Apply的妙用:
1、输出数组中最大的元素:
var arrs = [1,70,9,180,19,25,100,2,20]; function maxArrs(arrs){ return Math.max.apply('',arrs); } //console.log(Math.max(arrs)); //不能直接Math.max(数组变量),只能Math.max(1,70,9,180,19,25,100,2,20);否则输出NaN; console.log(maxArrs(arrs));
2、数组的push方法:
var arrs1=[5,1,3],arrs2=[3,1,5]; Array.prototype.push.apply(arrs1,arrs2); //[5, 1, 3, 3, 1, 5] //arrs1.push(arrs2); //[5, 1, 3, [3, 1, 5]] console.log(arrs1);
如果用arrs1.push(arrs2),输出的是[5,1,3,[3,1,5]],这样是把arrs2整个数组当成一个元素添加到arrs1,而不是依次添加.