全国统一服务热线:400-633-9193

JavaScript中this关键字用法实例分析

    网络     2018-09-30    1233

本文实例总结了JavaScript中this关键字用法。分享给大家供大家参考,具体如下:

例1:

1
2
3
4
5
6
function a(){
  var user = "yao";
  console.log(this.user);//undefined
  console.log(this);//window
}
a();

等价于:

1
2
3
4
5
6
function a(){
  var user = "yao";
  console.log(this.user);//undefined
  console.log(this);//window
}
window.a();

this指向的是window。

例2:

1
2
3
4
5
6
7
var o = {
  user:"yao",
  fn:function () {
    console.log(this.user);//yao
  }
}
o.fn();

this指向的是o。

例3:

1
2
3
4
5
6
7
var o = {
  user:"yao",
  fn:function () {
    console.log(this.user);//yao
  }
}
window.o.fn();

this指向的是o。

1
2
3
4
5
6
7
8
9
10
var o = {
  a:10,
  b:{
    a:12,
    fn:function () {
      console.log(this.a);//12
    }
  }
}
o.b.fn();

this指向的是b。

例4:

1
2
3
4
5
6
7
8
9
10
11
12
var o = {
  a:10,
  b:{
    a:12,
    fn:function () {
      console.log(this.a);//undefined
      console.log(this);//window
    }
  }
};
var j = o.b.fn;
j();

综上所述:

this的指向永远是最终调用它的对象。

当this遇上函数的return:

例5:

1
2
3
4
5
6
function fn(){
  this.user = "yao";
  return {};
}
var a = new fn;
console.log(a.user);//undefined

例6:

1
2
3
4
5
6
function fn(){
  this.user = "yao";
  return function(){};
}
var a = new fn;
console.log(a.user);//undefined

例7:

1
2
3
4
5
6
function fn(){
  this.user = "yao";
  return 1;
}
var a = new fn;
console.log(a.user);//yao

例8:

1
2
3
4
5
6
function fn(){
  this.user = "yao";
  return undefined;
}
var a = new fn;
console.log(a.user);//yao

this指向的是函数返回的那个对象。

1
2
3
4
5
6
function fn(){
  this.user = "yao";
  return null;
}
var a = new fn;
console.log(a.user);//yao

虽然:null是对象,但是此时this指向的仍然是函数的实例。


  分享到:  
0.2438s