• js 函数中的this


    资料

    function 函数

    没有“this”的持久概念, 调用函数时,创建this

    function hello(thing) {
      console.log(this + " says hello " + thing);
    }
    
    person = { name: "Brendan Eich" }
    person.hello = hello;
    
    // 在person中调用 hello, this被创建到了person
    person.hello("world") // still desugars to person.hello.call(person, "world")
    
    // 在window中调用 this被创建到了 window
    hello("world") // "[object DOMWindow]world"
    

    引用具有持久this值的函数

    name = "global";
    
    var person = {
      name: "Brendan Eich",
      hello: function() {
        console.log(this.name);
      }
    };
    
    var boundHello = function(arguments) {
      return person.hello.apply(person, arguments);
    };
    boundHello(); // Brendan Eich
    
    let a = person.hello.bind(person);
    a(); // Brendan Eich
    
    let b = person.hello
    b() // global
    

    箭头函数

    箭头函数捕获this => 创建函数的位置 而不是调用它的位置

    箭头函数没有自己的this, 箭头函数内部的上下文在函数的整个生命周期中保持不变, 并且始终将this绑定到最接近的非箭头父函数中的上下文

    let o = {
      a: 'ajanuw',
      hello: function(){
        //  返回箭头函数时,this已经被绑定了
        return () => {
          console.log(this.a)
        }
      }
    }
    
    let a = o.hello()
    a()
    
  • 相关阅读:
    队列01--[队列&双端队列&循环队列&双端循环队列]
    LeetCode--[栈]--不定时更新
    栈01--[栈接口设计&&栈应用]
    初等数论初步
    成外国庆集训小记
    图论算法初步
    Are Lights Still On?
    二分答案和三分入门
    SCOI2010 传送带
    微信小程序 菜鸟笔记
  • 原文地址:https://www.cnblogs.com/ajanuw/p/9819916.html
Copyright © 2020-2023  润新知