zoukankan      html  css  js  c++  java
  • this指向问题

    经常在代码中使用this,但是没有总结过this指向的问题。

      var name = "Jake";
      function testThis() {
        this.name = 'jakezhang';
        this.sayName = function () {
          return this.name;
        }
      }
    console.log('第一个this===', this); // this指向window console.log(this.name); // Jake new testThis(); console.log('第二个this', this); console.log(this.name); // Jake var result = new testThis(); // 谁被new,指向谁 console.log('第三个this=', this); // this指向构造函数 console.log(result.name); // jakezhang console.log(result.sayName()); // jakezhang testThis();
     console.log('第四个this=', this); console.log(this.name); // jakezhang

    解析:

    1.第一个this:在全局范围内,this指向window对象;

     所以this.name = 'Jake';指向最外层的name

    2.第二个this:有new关键字, 但是没有任何对象接收这个构造函数,所以此时的this还是指向window的。

     所以this.name = 'Jake'

    3.第三个this:相当于生成一个构造函数,并赋值给result,此时还是谁被new,指向谁。this指向testThis();

     result.name = 'jakezhang';

    4.第四个this:调用testThis()函数,this指向函数内部

     this.name = 'jakezhang'

    注解:

    为什么函数被调用的时候,this指向函数?

    函数被调用(函数运行时)才会确定函数内的this指向。
    因为函数中的this和arguments是两个特殊的变量,在函数被调用的时候才能取到他们。而且这两个变量只会在活动对象范围内。

      

  • 相关阅读:
    团队冲刺-1
    最优惠购买书籍
    gogoing软件NABCD
    二维数组首尾相连
    首尾相连一维数组的最大子数组和
    二维数组返回最大子矩阵之和
    石家庄铁道大学基础教学楼电梯使用调查
    子数组最大值求和
    返回一个整数数组中最大子数组的和-课堂训练(子数组为连续)
    软件工程概论-四则运算
  • 原文地址:https://www.cnblogs.com/liumcb/p/14061388.html
Copyright © 2011-2022 走看看