zoukankan      html  css  js  c++  java
  • 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。

      

  • 相关阅读:
    打开百度要用几步
    web渗透总结
    mysql之基本数据类型
    网络编程
    垃圾回收机制
    常用模块-hashlib,hmac,configparser,subprocess,xlrd,xlwt,xml,re
    常用模块-random,shutil,shevle,logging
    文件操作
    元组、字典、集合数据类型
    基本数据类型之列表类型
  • 原文地址:https://www.cnblogs.com/xuhua123/p/11649947.html
Copyright © 2011-2022 走看看