zoukankan      html  css  js  c++  java
  • js this理解

    原文链接:http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html

     this是js语言的几个关键字,代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。

    比如

    function test(){
      this.x = 1;
    }

     随着函数使用场合不同,this的值发生变化,但是有一个原则那就是,this指的是调用函数的那个对象

    情况一

    请看下面这段代码,它的运行结果是1。

      function test(){

        this.x = 1;

        alert(this.x);

      }

      test(); // 1 

        //等价于 window.test(); 调用函数的那个对象----window,则window.x = 1;

    情况二:作为对象方法的调用

    函数还可以作为某个对象的方法调用,这时this就指这个上级对象。

      function test(){

        alert(this.x);

      }

      var o = {};

      o.x = 1;

      o.m = test;

      o.m(); // 1   

        //调用函数的那个对象 ---- 对象o,则o.x = 1

    情况三 作为构造函数调用

    所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。

      function test(){

        this.x = 1;

      }

      var o = new test();

      alert(o.x); // 1

    情况四 apply调用

    apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。

      var x = 0;

      function test(){

        alert(this.x);

      }

      var o={};

      o.x = 1;

      o.m = test;

      o.m.apply(); //0

          //等价于 o.m.apply(this)      也等价于 o.m.apply(window)  相当于window.m(); 调用函数的那个对象-----window   window.x = 0

    apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。

    如果把最后一行代码修改为

      o.m.apply(o); //1

           //等价于 o.m(); 调用函数的那个对象 ----- 对象O  o.x=1

    运行结果就变成了1,证明了这时this代表的是对象o。

  • 相关阅读:
    【LeetCode】Validate Binary Search Tree
    【LeetCode】Search in Rotated Sorted Array II(转)
    【LeetCode】Search in Rotated Sorted Array
    【LeetCode】Set Matrix Zeroes
    【LeetCode】Sqrt(x) (转载)
    【LeetCode】Integer to Roman
    贪心算法
    【LeetCode】Best Time to Buy and Sell Stock III
    【LeetCode】Best Time to Buy and Sell Stock II
    CentOS 6 上安装 pip、setuptools
  • 原文地址:https://www.cnblogs.com/wxiaona/p/6023509.html
Copyright © 2011-2022 走看看