首页 > Web开发 > 详细

js this的指向

时间:2016-01-28 12:31:31      阅读:240      评论:0      收藏:0      [点我收藏+]

this是javascript语言中的一个关键字,它是函数运行时自动生成的一个内部对象,只能在函数内部使用。一般情况下,this指向的是调用函数的那个对象。

(1)作为普通函数直接调用,this指向window

function fun(){
  this.age = 1;
}
fun();

函数fun中的this指向是window,即

function fun(){
  this.age = 1;
}
fun();
console.log(age);//输入1

这里的age相当于全局变量age,能被其他函数调用,如果代码改为

function fun(){
  var age = 1;
}
fun();
console.log(age);//报错,age is not defined,这里的age是fun()中的局部变量

还有一种函数调用,及嵌套函数:

function fun(){
  function inner(){
    this.age = 1;      
  }
  inner();
}
fun();
console.log(age);//输入1

这里的this指向仍然是window,即还是全局变量,但此处的inner()是fun()中的对象,不能直接在fun外调用。

(2)作为对象方法调用

var age = 2;    
var test = {
  age: 1,
  show: function(){
    console.log(this.age);//输出1,此处的this指向的是test对象
  }
}
console.log(this.age);//输出2,此处的this指向的是window,并不受test对象age的影响
test.show();

(3)作为构造函数调用

构造函数是指通过这个函数生成一个新的对象。这时,this指向这个新的对象。

var age = 2;    
function test(){
  this.age = 1;
}
var tt = new test();
tt.show = function(){
  console.log(this.age);//输出1,此时this指向tt
}
tt.show();
console.log(this.age);//输出2,由此可见,构造函数中的this不会影响到全局变量

(4)call/apply 调用,改变this的指向

var age = 1;
function show(){
  this.age = 3;
}
function test(){
  this.age = 2;
}
show.call(test);//test继承了show里的方法及属性,此时,show中的this指向的是test
console.log(test.age);//输出3

还有一些this,比如在click事件中,this指向的是操作的节点元素;ajax中的this指向的就是ajax里的内部对象了。

 

js this的指向

原文:http://www.cnblogs.com/cyj7/p/5164255.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!