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是两个特殊的变量,在函数被调用的时候才能取到他们。而且这两个变量只会在活动对象范围内。

      

  • 相关阅读:
    pycharm上传代码到github中
    requests的封装(user-agent,proxies)
    Flask
    CTBCMCLibUser类
    TB timer 的用法
    多个 additional include directories 的复制方法
    怎样在编译时不显示警告
    infragistics 循环每一个选中的行
    Infragitics ultra grid 实现点击某一个cell的时候选中整行,并且不可编辑
    c#转换 datetime
  • 原文地址:https://www.cnblogs.com/liumcb/p/14061388.html
Copyright © 2011-2022 走看看