zoukankan      html  css  js  c++  java
  • this的指向

    1.this指向它的调用对象

    function getA(){
      var a = 1;
      console.log(this); //window
      console.log(this.a); //undefined
    }
    getA();  //等价于window.getA()
     
    var getA={
      a:"1",
      fn:function(){
        console.log(this.a) //1
      }
    }
    getA.fn();  //此时this指向对向getA
     
    var getA={
      a:1,
      fn:function(){
        console.log(this.a) //1
      }
    }
    window.getA.fn(); //此时this仍然指向getA(),this只会指向他的上一级
     
    var getA={
      a:1,
      b:{
        a:5,
        fn:function(){
          console.log(this.a); //5
        }
      }
    }
    getA.b.fn();
     
    var getA={
      a:1,
      b:{
        a:5,
        fn:function(){
          console.log(this.a); //undefined
        }
      }
    }
    var c = getA.b.fn;
    c(); //fn赋值给变量C时没有执行,所以最终指向是window
     
    2.new会改变this的指向
     
    function getA(){
      this.a = 1;
    }
    var b = new getA();
    console.log(b.a);  //1,new等于将getA()复制了一份到对象B中
     
    function getA(){
      this.a = 1;
      return{};
    }
    var b = new getA();
    console.log(b.a); //undefiend
     
    function getA(){
      this.a = 1;
      return function(){};
    }
    var b = new getA();
    console.log(b.a); //undefiend
     
    function getA(){
      this.a = 1;
      return 1;
    }
    var b = new getA();
    console.log(b.a); //1
     
    function getA(){
      this.a = 1;
      return undefined;
    }
    var b = new getA();
    console.log(b.a); //1
     
    function getA(){
      this.a = 1;
      return null;
    }
    var b = new getA();
    console.log(b.a); //1
     
    3.call,apply会改变this指向
     
    var getA={
      a:1,
      fn:function(){
        console.log(this.a);  
      }
    }
    var b = getA.fn;
    b.call(getA);
     
    call可以添加多个参数
    var getA={
      a:1,
      fn:function(c,d){
        console.log(this.a); //1
        console.log(c+d); //7
      }
    }
    var b = getA.fn;
    b.call(getA,3,4);
     
    apply与call类似,但是apply的第二个参数必须是数组
    var getA={
      a:1,
      fn:function(){
        console.log(this.a); //1
      }
    }
    var b = getA.fn;
    b.apply(getA);
     
    var getA={
      a:1,
      fn:function(c,d){
        console.log(this.a); //1
        console.log(c+d); //7
      }
    }
    var b = getA.fn;
    b.call(getA,[3,4]);
     
    如果call和apply的第一个参数写的是null,则指向window
  • 相关阅读:
    [Qt] 文本文件读写, 摘自官方文档
    [Windows] Socket Server Failed to bind, error 10048
    lodctr /R 失败的情况
    ModuleNotFoundError: No module named 'sklearn.cross_validation'
    [Qt] 通过socket将另一个程序的某个窗口调到最前端
    SortedDictionary<TKey, TValue> 类 表示根据键进行排序的键/值对的集合。
    finally不管有没有错都会运行 finally 块用于清除 try 块中分配的任何资源,以及运行任何即使在发生异常时也必须执行的代码
    HttpWebRequest使用证书请求
    string StartsWith 方法 Https
    设置https验证方式
  • 原文地址:https://www.cnblogs.com/wha000/p/11357312.html
Copyright © 2011-2022 走看看