1、在全局函数中this指的是window
2、当函数被当做方法调用时,this等于那个对象
3、匿名函数具有全局性,只要是匿名函数,this指向window
实例1:
var name = 'the window'; var obj = { name:'the obj', getName:function(){ return function(){ return this.name } } }; console.log(obj.getName()());//the window
由于最后返回的是匿名函数,所以this指向为window,结果为the window
实例2:
var name = 'the window'; var obj = { name:'the obj', getName:function(){ var _this = this; return function(){ return _this.name } } }; console.log(obj.getName()());
我们可以借助闭包,声明一个变量_this,把当前的对象付给_this,然后调用_this上边的属性