码迷,mamicode.com
首页 > Web开发 > 详细

js随笔-函数方法中的this

时间:2017-07-03 13:56:54      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:function   tag   错误   创建   return   logs   nbsp   his   console   

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

  

js随笔-函数方法中的this

标签:function   tag   错误   创建   return   logs   nbsp   his   console   

原文地址:http://www.cnblogs.com/Anne3/p/7110547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!