您的位置:首页 > Web前端 > JavaScript

javascript之var self = this

2015-12-09 11:05 459 查看
在js代码中,经常可以看到有如下的一个语句:

var self = this;


之所以写这个语句,是因为在一个对象内部,this指向的是这个

对象,而在普通函数内部,this指向的是window对象。所以不能在

普通函数里面用this来访问对象的属性,如下:

function a(){
this.name = "hello";

function b(){  //b只是一个普通函数,不是a的属性方法
alert(this.name);
}
b();  //调用b
}

new a(); //新建一个a对象,此时alert name undefined


所以如果你在一个对象里面定义了一个普通函数(注意不是该对象的属性函数),

为了能够在该普通函数里面访问到对象的属性,可以先把对象的this

赋值给一个变量(如self),然后再在该普通函数里面通过self

来获取到对象的属性,如下:

function a(){
var self = this;
this.name = "hello";

function b(){  //b只是一个普通函数,不是a的属性方法
alert(self.name);
}
b();  //调用b
}

new a(); //新建一个a对象,此时alert name = hello


同时,在对象内部定义的匿名函数的this指针也是指向window对象,而不是该对象,看如下例子:

var param = "hello";
var myObject = {
param: 123,
method: function(){
alert( this.param );  //this指向myObject
},
method2: function(){
setTimeout(function(){  //匿名函数
alert( this.param ); //this指向windows
},100);
}
}
myObject.method(); //alert 123
myObject.method2();  //alert hello


总结一下,如果不是为了在其他函数中访问到对象的属性,很多时候我们是不用写var self = this这句代码的。

var self = this这句代码是为了能让其他函数访问到对象的属性,因为在不同的作用域内,this的指向是不同的。

如果对this指针的指向不是很明白的,可以看我的这篇文章:http://blog.csdn.net/liujan511536/article/details/50233097
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: