call、apply、bind方法分析及应用

时间:2021-03-17 14:11:32   收藏:0   阅读:0

call

   // call
   // 类数组对象  ,它就没有数组Array的原型对象prototype上的方法,比如push、splice等
    var o = {
        0:11,
        1:22,
        2:33,
        3:44,
        length:4
    };
    console.log(o);
    //当增加一项数据时
    o["4"] = 55;
    o.length = 5;
    console.log(o);//需要将类数组对象中的length手动加 1

    //call()方法,可以改变this的指向
    Array.prototype.push.call(o,99);
    console.log(o);
    console.log(o.length);
    console.log(o[5]);

技术图片

apply

//apply 打散数组
          var arr = [2,3,8,90,1];
          console.log(1,2,3);
          console.log.apply(console,arr);

打散数组成散列式的
技术图片
可以让数组使用Math的max方法

var arr = [2,3,8,90,1];
  // 内置Js中的一些方法方法 
  console.log(Math.max(1,78,2,3));    
  //利用apply方法,将数组传给max的第二个参数
  console.log(Math.max.apply(Math,arr));
  //第一个参数this指向,还是指向Math本身,这里可以写Math,可以写null

bind

  //bind
  //修改定时器的函数内部的this
   var o = {
       name:"lili",
       age:12,
       years:function(){
           setInterval(function(){
               console.log(this.age);//定时器中的this指向的是window对象
           // 而window对象没有age,所以输出错误
           },1000)
       }
   };
   o.years();// window对象没有age,输出undefined

更改定时器中的this:

   years:function(){
         setInterval(function(){
              console.log(this.age);//定时器中的this指向的是window对象
          // 而window对象没有age,所以输出错误
          }.bind(this),1000)//更改this指向o
      }

更改事件函数中的this:

   //bind
  //修改定时器的函数内部的this
  var o = {
      name:"lili",
      age:12,
      years:function(){
          setInterval(function(){
              console.log(this.age);//定时器中的this指向的是window对象
          // 而window对象没有age,所以输出错误
          }.bind(this), 1000)//更改this指向
      }
  };
  o.years();// window对象没有age,输出undefined
  // 更改定时器中的this

  //更改 事件函数中的this指向
  document.onclick = function(){
      console.log(this);
  };
 

document的this指向
技术图片
更改document中的this指向o:

   document.onclick = function () {
                    console.log(this);
            }.bind(o);//指向o

技术图片

总结

call 和 apply特性一样

技术图片
技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!