用例子讲解JavaScript中this的指向

通过 updateInfo 来更新 userInfo 里面的数据信息,但是这段代码存在一些问题,你能修复这段代码吗?

let userInfo = {
  name:"jack.ma",
  age:13,
  sex:male,
  updateInfo:function(){
    //模拟xmlhttprequest请求延时
    setTimeout(function(){
      this.name = "pony.ma"
      this.age = 39
      this.sex = female
    },100)
  }
}

userInfo.updateInfo()

方法一箭头函数(ES6 中的箭头函数并不会创建其自身的执行上下文,所以箭头函数中的 this 取决于它的外部函数。)

let userInfo = {
    name:'jack.ma',
    age:13,
    sex:'male',
    updateInfo:function(){
        setTimeout(()=>{
            this.name='pony.ma';
            this.age=30;
            this.sex='female';
           console.log(this);
        },100);
    }
};
userInfo.updateInfo();     

方法二:缓存外部的this

let userInfo = {
    name:'jack.ma',
    age:13,
    sex:'male',
    updateInfo:function(){var self = this;
        setTimeout(function(){
            self.name='pony.ma';
            self.age=30;
            self.sex='female';
            console.log(self);
        },100);
    }
};
userInfo.updateInfo();

方法三:立即执行函数(跟方法二思路是相同的)

let userInfo = {
    name:'jack.ma',
    age:13,
    sex:'male',
    updateInfo:function(){
        (function(self){
            setTimeout(()=>{
                self.name='pony.ma';
                self.age=30;
                self.sex='female';
                console.log(self);
        },100);
    })(this)}
};
userInfo.updateInfo();

方法四:可以用userInfo作为setTimeout的第三个参数(跟方法二思路是相同的)

let userInfo = {
    name:'jack.ma',
    age:13,
    sex:'male',
    updateInfo:function(){
        setTimeout(function(self){
            self.name='pony.ma';
            self.age=30;
            self.sex='female';
            console.log(self);
        },100,userInfo);
    }
};
userInfo.updateInfo();    

方法五:利用call或apply修改函数被调用时的this值

let userInfo = {
    name:'jack.ma',
    age:13,
    sex:'male',
    updateInfo:function(){
        setTimeout(function(){
            update.call(userInfo);
       // update.apply(userInfo); },100); } }; function update(){ this.name='pony.ma'; this.age=30; this.sex='female'; } userInfo.updateInfo();

方法六:利用bind返回一个新函数,新函数被调用时的this指定为userInfo

let userInfo = {
    name:'jack.ma',
    age:13,
    sex:'male',update:
        function(){
        this.name='pony.ma';
        this.age=30;
        this.sex='female';
    },
    updateInfo:function(){
        setTimeout(this.update.bind(this),100);
    }
};
userInfo.updateInfo();
原文地址:https://www.cnblogs.com/youknowUL/p/12197927.html