zoukankan      html  css  js  c++  java
  • 关于javascript中this的运用

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

    1、纯粹函数调用。

      function test(){

        this.x = 1;

        alert(x);

      }

      其实这里的this就是全局变量。看下面的例子就能很好的理解其实this就是全局对象Global。

      var x = 1;

      function teast(){

        alert(this.x);

      }

      teast();//1

     

      var  x = 1;

      function test(){

        this.x = 0;

      }

      test();

      alert(x);//0

     

    2、作为方法调用,那么this就是指这个上级对象。

     function test() {
    
    alert(this.x);
    }

    var o = {};
    o.x = 1;
    o.m = test;
    o.m(); //1

    3、作为构造函数调用。所谓构造函数,就是生成一个新的对象。这时,这个this就是指这个对象。

      function test() {
    
      alert(this.x);
      }

    var o = {};
    o.x = 1;
    o.m = test;
    o.m(); //1
      function test() {
    
    alert(this.x);
    }

    var o = {};
    o.x = 1;
    o.m = test;
    o.m(); //1


    4、apply调用

           this指向的是apply中的第一个参数。

       var x = 0;
    
    function test() {
    alert(this.x);
    }

    var o = {};
    o.x = 1;
    o.m = test;
    o.m.apply(); //0
    o.m.apply(o);//1

    当apply没有参数时,表示为全局对象。所以值为0。

  • 相关阅读:
    Linux系统下ZIP文件解压和压缩命令
    解析XML文件
    数组和集合之间的转换
    数据库密码到期修改密码
    Linux系统中启动jar程序
    JSONArray依赖包
    多态性
    接口----interface
    抽象类
    final关键字
  • 原文地址:https://www.cnblogs.com/Tommy1014/p/3945627.html
Copyright © 2011-2022 走看看