js this指向和call apply bind方法

this指向

关于this指向,我们可以理解为哪个对象调用函数,函数里面的this指向哪个对象。

      function a( ){          

              console.log(this) ;//this(window)

     }        

      a( );


    function b( ) { 

           console.log(this);//this(b函数对象)

       } 

       new   b( );


总结一下就是函数a为普通函数对象,这种函数对象执行的this是window,函数b为构造函数对象,它的this是调用的函数对象


call apply  bind的用法


        var obj = {

            name:'张三',  

            say:function(str,str2){

                console.log(this.name+'  '+str+'  '+str2)  // 李四 hello world         

         }       

 }

   var f =  obj.say.call({name:'李四'},'hello','world');      

//   call() 可以调用函数,也可以改变函数this的指向


        var obj={

            name:'张三',

            say:function(str,str2){
                    conlose.log(this.name+' '+str+' 'str2)   //  李四  hello world

    }

}

    var  f=  obj.say.bind({name:'李四'},'hello','world');

    f(  )

//bind方法使用的时候需要再次调用



        var obj={

            name:'张三',

            say:function(str,str2){

                    conlose.log(this.name+' '+str+' 'str2)   //  李四  hello world

    }

}

    var  f=  obj.say.apply({name:'李四'},['hello','world']);

//使用apply方法改变this指向时参数需要以数组形式表达


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容