zoukankan      html  css  js  c++  java
  • apply()、call()、bind()改变作用域

    相同点

    • 三者都是用来改变函数体内部 this 的指向;
    • 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
    • 三者都可以利用后续参数传参;

      不同点

    • bind是返回对应函数,便于稍后调用;apply、call则是立即调用
    • apply、call接收参数的方式不一样
    func.call(this, arg1, arg2);
    func.apply(this, [arg1, arg2]);
    • bind()提供永久的绑定,还会覆盖后面的callapply命令。使用bind()绑定后,再使用call()或者apply()来不能重新绑定this
    function returnThis () {
      return this
    }
    var boss1 = { name: 'boss1'}
    var boss1returnThis = returnThis.bind(boss1)
    boss1returnThis() // boss1
    var boss2 = { name: 'boss2' }
    boss1returnThis.call(boss2) // still boss1
    boss1returnThis.apply(boss2) // still boss1
    boss1returnThis.bind(boss2) // boss2
  • 相关阅读:
    Wiggle Sort II
    Coin Change
    MPLS LDP 知识要点
    MPLS Aggreate & Untag
    Lab MPLS隐藏标签显示
    Lab MPLS过滤标签转发
    MPLS MTU Aggregation
    研究MPLS MTU的问题
    Lab 利用MPLS解决BGP路由黑洞
    MPLS 标签保留
  • 原文地址:https://www.cnblogs.com/Zting00/p/7497647.html
Copyright © 2011-2022 走看看