JS中this的作用

来源:互联网 发布:通信网络设计师是什么 编辑:程序博客网 时间:2024/05/21 21:37

JS中this的作用

构造器中的this

var Obj = function(){  this.value = 'a';  this.getValue = function(){    console.log(this.value);  }}var obj = new Obj();obj.getValue();

输出:

"a"

这里类构造时的this就是指Obj这个“类”。this.value是指,这个“类”中的成员属性。

作为对象方法调用

var Obj = function(){  this.value = 'a';  this.getValue = function(){    console.log(this.value);  }}var obj = new Obj();obj.getValue();

输出:

"a"

getValue这个方法,通过“对象”的方式进行调用。其中的this.value就是指这个对象中的属性,this指这个对象。

作为普通方法调用

var Obj = function(){  this.value = 'a';  this.getValue = function(){    console.log(this.value);  }}var obj = new Obj();var fun = obj.getValue;fun();

输出:

undefined

由于getValue的调用不再通过对象直接调用,而是使用简单函数的方式进行调用,因此此时,this会丢失(指向全局window类,在ES5 restrict模式下,为undefined).
为了解决这个问题,我们可以提前在“对象”中先记录下,这个this,防止其丢失,然后再对这个记录进行读取操作。
如下:

var Obj = function(){  this.value = 'a';  var self = this;  this.getSelfValue = function(){    console.log(self.value);  }}var obj = new Obj();var funSelf = obj.getSelfValue;funSelf();

输出:

"a"
0 0
原创粉丝点击