理解js中this的指向
首先必须要说的是,this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象。
情况1:如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,这里需要说明的是在js的严格版中this指向的不是window,但是我们这里不探讨严格版的问题,你想了解可以自行上网查找。
情况2:如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。
情况3:如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象,
部分代码如下:
var obj = { birth: 1990, getAge: function () { var b = this.birth; // 1990 var fn = function () { console.log(this); // this指向window或undefined return new Date().getFullYear() - this.birth; }; return fn(); } };
var obj = { birth: 1990, getAge: function () { var b = this.birth; // 1990 var fn = function () { console.log(this); // 使用bind后this指向obj return new Date().getFullYear() - this.birth; }.bind(this); return fn(); } };