1. function getAge() {
    2. var y = new Date().getFullYear();
    3. return y - this.birth;
    4. }
    5. var xiaoming = {
    6. name: '小明',
    7. birth: 1990,
    8. age: getAge
    9. };
    10. console.log(xiaoming.age()); // 25, 正常结果
    11. console.log(getAge()); // NaN 此时this指向全局变量windows
    1. 'use strict'
    2. var xiaoming = {
    3. name: '小明',
    4. birth: 1990,
    5. age: function () {
    6. var that = this;
    7. console.log(that)
    8. function getAgeFromBirth() {
    9. var y = new Date().getFullYear()
    10. return y - this.birth;
    11. }
    12. return getAgeFromBirth()
    13. }
    14. }
    15. console.log(xiaoming.age()); //cannot read property birth of underfined
    16. //原因是this指针只在age方法的函数内指向xiaoming,在函数内部定义的函数,this又指向undefined了!(在非strict模式下,它重新指向全局对象window!)
    17. 修复的办法也不是没有,我们用一个that变量首先捕获this