bind , call && apply 使用

颓废就在那一瞬间,那段时间。

bind , call && apply 通俗的来讲就是,改变作用环境(this指向)。
this指向:最后调用它的对象,(匿名函数this指向window)

  • bind()

bind()
与call,apply区别:绑定之后然后--调用(不会立即执行)。
    const obj = {
        a: '1',
        b: '2'
    }
    function fun1(val) {
        console.log(this);
    }
    fun1.bind(obj)()      //打印 {a:'1',b:'2'}
  //如果不bind将会打印window
  • call && apply

call && apply
与bind区别:绑定之后立即执行
call与apply区别:call是apply的语法糖,call参数为单个参数,apply参数为数组
/*
  call
*/
    const obj = {
        a: '1',
        b: '2'
    }
    function fun1(val) {
        console.log(this, val);
    }
    fun1.call(obj, ['a', 'b', 'c'])
    //打印{a: "1", b: "2"} ,  ["a", "b", "c"]

/*
  apply
*/
   const obj = {
        a: '1',
        b: '2'
    }
    function fun1(val) {
        console.log(this, val);
    }
    fun1.call(obj, ['a', 'b', 'c'])
    //打印{a: "1", b: "2"} ,  "a"
  • 拓展关于new的过程
//构造函数
function fun(){...}

new fun{
  let obj={}
  obj.__proto__=fun.prototype
  let result=fun.call(obj,...)
  return typeof result === 'obj'?result:obj
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容