您的位置:首页 > 移动开发

Javascript中关于call()与apply()详解

2016-06-23 18:24 417 查看
今天写这篇博客,希望对大家会有帮助;

//  apply:方法能劫持另外一个对象的方法,继承另一个对象的属性
//  Function.apply(obj,args)方法能接受两个参数
//  obj:这个对象将代替Function类里的this对象
//  args:这个是数组,它将作为参数传给Function(args >>>> arguments)
//  call:和apply的意思一样,只不过是参数列表不一样
//  Function.call(obj,[param1[,param2[,...[,paramN]]]])
//  obj:这个对象将替代Function 类里的this对象。
//  params:这个是一个参数列表;

//apply实例

function Person(name,age){    // 定义一个人类
this.name = name;
this.age = age;
}
function Student(name,age,grade){  //   定义一个学生类
Person.apply(this,arguments); // this在创建对象在这时候代表的是student;
this.grade = grade;
}
var student = new Student('梁朝伟',21,'一年级');// new 一个学生对象
console.log("name:"+student.name +'-'+"age:"+student.age+'-'+"grade:"+student.grade)

//call实例

function Person1(name,age){
this.name =name;
this.age = age;
}
function Student1(name,age,grade){
Person1.call(this,name,age);
this.grade = grade;
}
var student1 = new Student1('刘德华',64,'已毕业');
console.log("name:"+student1.name +'-'+"age:"+student1.age+'-'+"grade:"+student1.grade);

// 提示:什么情况下用apply,什么情况下用call;
//  在给对参数的情况下,如果参数的形式是数组的时候,比如apply实例里面传递了参数arguments,这个参数是数组类型,并且在调用Person
//  的时候参数列表是对应一致的(也就是Person和Student的参数列表的前两位是一致的)就可以采用apply,如果我的Person的参数列表是这样的
//  (age,name),而Student的参数列表是(name,age,grade),这样就可以用call来实现了,也就是直接指定参数列表对应值的位置;
//  (Person.call(this,age,name,grade))

//  apply的一些其他巧妙用法
//  在我调用apply方法的时候,第一个参数是对象this,第二个参数是一个数组集合,在调用Person的时候,它需要的不是一个数组,但是为什么它给我的
//  一个数组我仍然可以将数组解析为一个一个参数,这个即使apply的一个巧妙用处,可以将一个数组默认的转换为一个参数列表
//  即([param1,param2,param3])转换为param1,param2,param3;

//  Math.max 可以实现得到数组中的最大的一项
//  因为Math.max参数里面不支持Math.max([param1,param2]),也就是数组
//  但是它支持Math.max(param1,parma2,parma3...),所以可以根据刚才apply的那个特点来解决
//  var max =Math.max.apply(null,array)
var max= Math.max.apply(null,[1,23,78,100,666]);
console.log(max);  // 666
// 提示:这块在调用的时候第一个参数传给了一个null,这个是因为没有对象去调用这个方法,只需要用这个方法帮我运算,得到返回的结果就行,所以直接传递了一个null过去;

//  Math.min 可以实现得到数组中最小的一项
var min = Math.min.apply(null,[1,23,78,100,666]);
console.log(min);   //1

//  Array.prototype.contact()可以实现两个数组合并----------貌似只能实现两个数组合并,如果是多个数组的话,则不能适用;
var arr1 = ["1","2","3"];
var arr2 = ["4","5","6"];
var result = Array.prototype.concat.apply(arr1,arr2);
console.log(result);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Javascript apply call