开发中call、apply、bind的使用场景

174 阅读1分钟

一.apply、call、bind方法的定义

这三个方法都是Function对象上的方法
apply和call方法只是参数的不同
apply:能劫持另一个对象的方法,继承另一个对象的属性
Function.apply(obj,args)
obj:这个对象将代替Function类里的this对象
args:这个是数组,它将作为参数传给Function(args->arguments)

call:和apply的意思一样,只是参数列表不一样
Function.call(obj,param1)
obj:这个对象将代替Function类里this对象
params:这个是一个参数列表

bind:call类似,但是不同的是call调用后可以立即执行,但是bind需要一个变量进行接收之后再执行

二.练习

例子1function Person(name,age){
        this.name = name;
        this.age = age;
    }
    function Student(name,age,grade){
        Person.apply(this,arguments);
        this.grade = grade;
    }
    var student = new Student("zhangsan","21","一年级");
    //测试
    alert("name:"+student.name)
    alert("age:"+student.age)
    alert("grade:"+student.grade) 
分析:
    this:在创建对象在这个时候是代表的是student
    arguments:是一个数组,也就是["zhangsan","21","一年级"]
    通俗来说就是student去执行Person这个类里面的内容,在Person这个类里面存在this.name等之类的语句,这样就将属性创建到了student对象里
    //改成call
    Person.call(this,name,age)
 例子2var stu1 = {
         name:"Jack",
         age:18,
         say:function(shcool,grade){
             console.log(this.name+"今年"+shcool+"年级"+grade)
         }
     }
     var stu2 = {
         name:'Tom'
     }
     stu1.say.call(stu2,"清华","四");  //Tom今年清华年级四
     stu1.say.apply(stu2,["北大","三"]) //Tom今年北大年级三 
     var val = stu1.say.bind()
  应用:
      var arr = Array.prototype.slice.apply(arguements)  //arguements是类数组,类数组转数组