• This is this


    首先,我们来了解一下 this 的几种绑定方式:

      this的默认绑定:

     当一个函数没有明确的调用对象的时候,即作为独立函数调用时,this绑定到全局window对象。

    function  func() {
        console.log(this);
    }
    
    func()  //window

      this的隐式绑定:

     当函数被其他对象包含再其中时,这时this被隐式绑定到了这个对象中;因此,通过this可以直接访问到该对象中的其他属性。

    var foo = {name:'Lily'}
    var obj = {
        name: 'John',
        age: 20,
        sayName: function(){
            console.log(this === obj); 
            console.log(this.name);   
        }
    }
    obj.sayName();      //true  John
    foo.sayName = obj.sayName;
    foo.sayName();      //false  Lily

      this的显式绑定:

     调用call() 或 apply()方法来实现this的主动绑定

    var animals = [
        {species: 'Lion', name: 'King'},
        {species: 'Whale', name: 'Fail'}
      ];
      
      for (var i = 0; i < animals.length; i++) {
        (function (i) { 
          this.print = function () { 
            console.log('#' + i  + ' ' + this.species + ': ' + this.name); 
          } 
          this.print();
        }).call(animals[i], i);
      }
      //#0 Lion: King
      //#1 Whale: Fail

      this的new绑定:

     函数被执行new操作后,将创建一个新的对象,并将构造函数的this指向所创建的构造函数。

    function foo(name){
        this.name = name
    }
    
    var bar = new foo('John');
    console.log(bar.name); //John

      this的硬绑定

     当this被强制绑定后,无论之后任何调用该this都不变

    var a = 5;
    function foo(){
        console.log(this.a);
    }
    var obj = {
        a: 2
    }
    var bar = function(){
        foo.call(obj);
    }
    bar();           //2
    bar.call(window);//2

      

    说完上述几种this绑定的情况后,就要来说一下箭头函数中的this了:

      

    function foo() {
        return () => {
          return () => {
            console.log(this)
          }
        }
      }
      console.log(foo()()())   //window

      箭头函数中实际上并没有this箭头函数中的this只取决包裹箭头函数的第一个普通函数的this。在这个例子中,因为包裹箭头函数的第一个普通函数是foo,所以此时的this是window。

      

  • 相关阅读:
    c++实现的一个链栈
    VS2005_XP DDK_DS3.2安装说明
    驱动开发遇到的一些问题
    fatal error LNK1000解决方法
    C++文件依存关系---提高编译速度
    架构的一些心得
    CPU与GPU的一点理解
    看"C++动态链接库编程深入浅出"的一些笔录
    VC2008下提示找不到MSVCP90D.dll的解决办法
    DLL搜索顺序
  • 原文地址:https://www.cnblogs.com/xuhua123/p/11649947.html
Copyright © 2020-2023  润新知