为啥$http.里面的this要重新指定呢,我再$http里面打印this,跟在外面打印this结果是一样的呀。
为啥$http.里面的this要重新指定呢,我再$http里面打印this,跟在外面打印this结果是一样的呀。
为啥$http.里面的this要重新指定呢,我再$http里面打印this,跟在外面打印this结果是一样的呀。
2017-07-06
可以参考下面的例子:
/*5*/
"use strict";
var xiaoming={
name:"xiaoming",
birth:2007,
age:function(){
function getAge(){
var y=new Date().getFullYear();
return y-this.birth;
}
return getAge();
}
};
xiaoming.age();//es6.html:426 Uncaught TypeError: Cannot read property 'birth' of undefined
console.log(xiaoming.age());//在非strict模式下:NaN
//这是因为this指针只在age方法的函数内指向xiaoming,在函数内部定义的函数又指向undefined(在非strict模式下,它重新指向全局对象window!)。
/*6*/
//修复方法:用一个that变量首先捕获this。
"use strict";
var xiaoming={
name:"xiaoming",
birth:2007,
age:function(){
var that=this;//一开始就捕获this,可以放心地在其他方法内部定义其他函数,而不是吧所有的语句都写在同一个方法中。
function getAge(){
var y=new Date().getFullYear();
return y-that.birth;
}
return getAge();
}
};
// xiaoming.age();
console.log(xiaoming.age());//10举报