js function 中的this

对于function中的this,需要明确一点的是它只有在function执行的时候才能被确定。并且this指的是function的执行环境,也就是调用该方法的对象。

var user = {
    count:1,
    getCount:function(){
      return this.count;   
    }
}
console.log(user.getCount()); //1
var otherGetCount = user.getCount;
console.log(otherGetCount());  //undefined;

上面代码中奖getCount方法赋值给otherGetCount方法,当在全局环境中调用otherGetCount()方法时,此方法的执行环境为window。由于在window下未定义count,所以返回值为undefined。
可通过以下代码验证:

var count = 2;
var user = {
    count:1,
    getCount:function(){
      return this.count;   
    }
}
console.log(user.getCount()); //1
var otherGetCount = user.getCount;
console.log(otherGetCount());  //2;

你可能感兴趣的:(js function 中的this)