浅析this在ES5 和 ES6中使用的区别

this在ES5中默认指向window对象,在ES6的vue中默认指向Vue实例,基本没什么区别,都是指向最顶层的对象

ES5全局环境下,this 始终指向全局对象(window)

console.log(this.document=== document); // true
// 在浏览器中,全局对象为 window 对象:
console.log(this === window); // true
this.name = 'zhangsan';
console.log(window.name); // zhangsan

this在函数中的时候,指向的是这个函数的作用域,当在函数中出现回调等情况的时候,回调函数中的this作用域会变成指向该回调函数,因此一般会在函数中使用 var that = this来保存this。

例子:

searchMusic: function () {
    
    
      // 存数据,this在axios请求后会变
      var that = this;
      axios.get("https://autumnfish.cn/search?keywords=" + this.query).then(
        function (res) {
    
    
          // console.log(res.data.result.songs);
          that.musicList = res.data.result.songs;
          console.log(that.musicList);
        },
        function (err) {
    
    
          console.log(err);
        }
      );
    },

再例如ES5中 this 的指向,由于没有使用 var that = this 来保存this,它的作用域就会改变,this 的指向是该函数被调用的对象,也就是this.c{ } 这一块,此时调用this.a获取的是this.c{ }里面a的值

var factory = function(){
    
    
		   this.a = 'a';
		   this.b = 'b';
		   this.c = {
    
    
		        a:'1',
		        b:function(){
    
    return this.a}
		    }  
		};
		console.log(new factory().c.b()); 
		//结果:1

接着这个例子给他提前定义好var that = this,相当于把this保存在了that变量,此时在回调函数中使用that.a就相当于是用函数中的this了。

  var factory = function(){
    
    
	   this.a = 'a';
       this.b = 'b';
       var that = this;
		   this.c = {
    
    
		        a:'1',
		        b:function(){
    
    return that.a}
		    }  
		};
		console.log(new factory().c.b()); 
    //结果:a

而ES6新引入了箭头函数,在箭头函数中,this指向上下文对象,因此可以不用再写 var that=this了。

es6箭头函数没有自己的this
es6箭头函数里的this是外层代码块的this

猜你喜欢

转载自blog.csdn.net/weixin_45811256/article/details/109840936
今日推荐