1.对象的方法形式调用,fun.getAge()的this指向的是对象fun
var fun={
name:"lihui",
age:23,
getAge:function(){
console.log(fun.age);
}
}
fun.getAge();//23
2.当在对象方法中内嵌函数,内嵌函数中的this便指向的是全局对象window,不是对象了
var fun={
name:"lihui",
age:23,
getAge:function(){
function getAgeFun(){
console.log(this.age);
}
return getAgeFun();
}
}
fun.getAge();//underfined
要想在函数中把this指向对象需要在方法中将this赋值给一个变量,在函数中使用这个变量
var fun={
name:"xiaoming",
age:23,
getAge:function(){
var that=this;
function getAgeFun(){
console.log(that.age);
}
return getAgeFun();
}
}
fun.getAge();//23
之前经常在回调函数中犯这种错误,就经常在success中创建函数,并在函数中直接this.xxx使用对象的参数,就会出错
3.在对象方法中调用在外部创建的函数,函数中的this指向的也是window
function getAgeFun(){
console.log(this.age);
}
var fun={
name:"xiaoming",
age:23,
getAge:function(){
getAgeFun();
}
}
fun.getAge();//underfined
4.在将对象方法赋值给其他变量,this值也是指向window
var fun={
name:"xiaoming",
age:23,
getAge:function(){
console.log(this.age);
}
}
var fun2=fun.getAge;
fun2();//underfined