JS中箭头函数与普通函数this指向

var sum=()=>{
    return obj;
}
var obj = {
    birth: 1997,
    getAge: function () {
        var b = this.birth; 
        var fn = function () {
            return new Date().getFullYear() - this.birth; // this指向window或undefined
        };
        return fn();
    }
};
console.log(sum().getAge());  //输出NaN

var obj = {
    birth: 1997,
    getAge: function () {
        var b = this.birth; 
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
console.log(sum().getAge()); //输出22

你可能感兴趣的:(js)