• js call()、apply()、bind()


    call()、apply()、bind()

    相同点:都是改变this的指向

    区别一 如下所示   bind 返回的是一个新的函数,必须调用它才会被执行

    var name = 'lily', age = 11
        var person = {
          name: '剑姬',
          oAge: this.age,
          full: function() {
            return this.name + " " + this.age;
          }
        }
        var abc = {
          name: "郭磊",
          age: 16
        }
      
    
    person.full() // 剑姬 undefined
    person.full.call(abc) // 郭磊 16
    person.full.apply(abc) // 郭磊 16
    person.full.bind(abc)() // 郭磊 16

    区别二 如下:call() 的第二个参数是字符串 

                 apply() 的所有参数必须放在数组里

               bind() 除了返回函数以外,其他的跟call()一样

    var name = 'lily', age = 11
        var person = {
          name: '剑姬',
          oAge: this.age,
          full: function(from, to) {
            return `${this.name} ${this.age} ${from} ${to}`;
          }
        }
        var abc = {
          name: "郭磊",
          age: 16
        }
    
        console.log(person.full.call(abc, '北京', '山东'))  //郭磊 16 北京 山东
        console.log(person.full.apply(abc, ['北京', '山东']))  //郭磊 16 北京 山东
       console.log(person.full.bind(abc, '北京', '山东')) //函数体
        console.log(person.full.bind(abc, ['北京', '山东'])())  //郭磊 16 北京,山东 undefined

      

  • 相关阅读:
    X-Plosives (并查集)
    HDU1272小希的迷宫 (并查集)
    React 初学
    js 插件 issue
    js常用方法
    常用网址
    js 零零散散的总结。
    git 常用命令
    es6 babel编译
    屏幕适配
  • 原文地址:https://www.cnblogs.com/guoxianglei/p/13646675.html
Copyright © 2020-2023  润新知