js的call()和apply()方法的理解

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值