码迷,mamicode.com
首页 > Web开发 > 详细

JS中this的四种用法

时间:2018-11-01 20:31:32      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:div   global   var   javascrip   java   lan   test   bsp   全局   

简而言之,就是function的this永远指向调用它的对象。而鉴于JS所谓的“万物皆对象”,这个this因此可以是任何物件,比如Global对象。

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

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

JS中this的四种用法

标签:div   global   var   javascrip   java   lan   test   bsp   全局   

原文地址:https://www.cnblogs.com/ximao/p/9892140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!