call()方法:
》》通过call(),我们可以使用属于另一个对象的方法
var person = {
fullName :function(){
return this .firstName + " " +this .lastName;
}
}
var person1 = {
firstName : "Bill",
lastName : "Gates",
}
var person2 = {
firstName : "Steve",
lastName : "Jobs",
}
conslole.log(person.fullName.call( person1)); // Bill Gates >>>>使对象person1使用对象person的fullName方法
》》call()方法接收参数
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA"); // Bill Gates,Seattle,USA
》》在另一个方法中使用,下面的apply也可使用同样的方式,只是传递的参数不一样,如var student = new Student('小明', [21, '大三']);
function People(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, grade) {
People.call(this, name, age); >>>>>使this(即Student方法)拥有People的方法
this.grade = grade;
}
var student = new Student('小明', 21, '大三');
console.log(student.name + student.age + student.grade);//小明21大三
**********************************************
apply()方法和call() 方法的不同之处:call()方法分别接受参数,apply()方法接收数组形式的参数
**************************************************
apply() 方法 您能够编写用于不同对象的方法
》》person的fullName方法被应用到person1
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName: "Bill",
lastName: "Gates",
}
person.fullName.apply(person1); // 将返回 "Bill Gates"
》》带参数
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]); //Bill Gates,Seatle,USA
》》在数组上模拟max方法,还有模拟min方法,如Math.min.apply(0,[1,2,3]),还有其他等等
Math.max(1,2,3); //返回3
//但是数组没有max方法,于是有了下面的例子,第一个参数无关紧要
Math.max.apply( null , [1,2,3] ); //返回3 >>>>>>>使null对象使用Math对象的max方法
Math.max.apply(Math, [1,2,3]); // 也会返回 3 >>>>>>>使Math对象使用Math对象的max方法
Math.max.apply(" ", [1,2,3]); // 也会返回 3
Math.max.apply(0, [1,2,3]); // 也会返回 3