zoukankan      html  css  js  c++  java
  • JS中this的四种用法

    1.在一般函数方法中使用 this 指代全局对象

    1
    2
    3
    4
    5
    function test(){
        this.x = 1;
        alert(this.x);
      }
      test(); // 1

    2.作为对象方法调用,this 指代上级对象

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

    3.作为构造函数调用,this 指代new 出的对象

    复制代码
      function test(){
        this.x = 1;
      }
      var o = new test();
      alert(o.x); // 1
        //运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:
      var x = 2;
      function test(){
        this.x = 1;
      }
      var o = new test();
      alert(x); //2
    复制代码

    4.apply 调用 ,apply方法作用是改变函数的调用对象,此方法的第一个参数为改变后调用这个函数的对象,this指代第一个参数

    复制代码
      var x = 0;
      function test(){
        alert(this.x);
      }
      var o={};
      o.x = 1;
      o.m = test;
      o.m.apply(); //0
    //apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。如果把最后一行代码修改为
    
      o.m.apply(o); //1
  • 相关阅读:
    POJ 2411 Mondriaan's Dream -- 状压DP
    codeforces 792A-D
    codeforces 796A-D
    Acdream1201 SuSu's Power
    HDU 2818 Building Block
    C# NetStream
    基于Duff's Device的C简易无栈协程实现
    CentOS 多版本 GCC 共存
    2017杭电多校第一场
    2019杭电多校第十场
  • 原文地址:https://www.cnblogs.com/wangshengli520/p/8641826.html
Copyright © 2011-2022 走看看