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
  • 相关阅读:
    [LeetCode] 67. 二进制求和
    [LeetCode] 66. 加一
    [LeetCode] 65. 有效数字
    [LeetCode] 63. 不同路径 II
    [LeetCode] 64. 最小路径和
    [LeetCode] 61. 旋转链表
    [LeetCode] 62. 不同路径
    [LeetCode] 59. 螺旋矩阵 II
    [LeetCode] 60. 第k个排列
    [LeetCode] 58. 最后一个单词的长度
  • 原文地址:https://www.cnblogs.com/wha000/p/11357312.html
Copyright © 2011-2022 走看看