JavaScript中的this指向问题

this是Javascript语言的一个关键字。

它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。比如,

  function test(){

    this.x = 1;

  }

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

下面分四种情况,详细讨论this的用法。

情况一:纯粹的函数调用

这是函数的最通常用法,属于全局性调用,因此this就代表全局对象Global。

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

  function test(){

    this.x = 1;

    alert(this.x);

  }

  test(); // 1

为了证明this就是全局对象,我对代码做一些改变:

  var x = 1;

  function test(){

    alert(this.x);

  }

  test(); // 1

运行结果还是1。再变一下:

  var x = 1;

  function test(){

    this.x = 0;

  }

  test();

  alert(x); //0

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

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

  function test(){

    alert(this.x);

  }

  var o = {};

  o.x = 1;

  o.m = test;

  o.m(); // 1

情况三 作为构造函数调用

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

  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

运行结果为2,表明全局变量x的值根本没变。

情况四 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

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

// 以下代码输出什么?为什么?


var app={


  fn1 : function(){

    console.log(this); //app  

  },

  fn2 : function(){

    return function(){

      console.log(this);//window

    }

  },

  fn3 : function() {

    function fn() {

      console.log(this) //window 闭包里的this和argument不能拿外面的那个函数里的

    }

    fn();  

  },

  fn4 : function(){

    return {

       fn:function(){

         console.log(this); //fn函数 app.fn4().fn(); app.fn4()调用时 返回一个对象 这个对象里面有{fn函数} {fn函数}.fn() 对象调用方法时 this指向该对象

       }

    }

  },

  fn5() {

    setTimeout(function(){

      console.log(this) //输出window 解释:setTimeout 将函数放入异步队列中,根据Event Loop原理图,异步队列中的函数总是
//在全局环境的作用栈上执行 因此this指向宿主环境

    },10)

  },

  fn6() {

    setTimeout(()=>{

      console.log(this) //app对象 箭头函数不绑定this 箭头函数中的this值与定义该函数的上下文有关 所以指向app

    },20)

  },

  fn7() {

    setTimeout((function(){

      console.log(this) //app对象???

    }).bind(this),30)

  },

  fn8 : ()=>{

    setTimeout(()=>{

      console.log(this) //{}???

    },40)

  }

}
// app.fn1();
// app.fn2()();
// app.fn3();
// app.fn4().fn();
// app.fn5();
// app.fn6();
// app.fn7();
app.fn8();

猜你喜欢

转载自www.cnblogs.com/cmy1996/p/9103054.html