Analysis of the difference between this in ES5 and ES6

This points to the window object by default in ES5, and points to the Vue instance by default in Vue of ES6 . There is basically no difference, and they all point to the topmost object .

In the ES5 global environment, this always points to the global object (window)

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

When this is in a function, it points to the scope of this function. When there is a callback in the function, the scope of this in the callback function will change to point to the callback function, so var is generally used in the function that = this to save this.

example:

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);
        }
      );
    },

Another example is the point of this in ES5. Since var that = this is not used to save this, its scope will change. The point of this is the object on which the function is called, which is this.c{ }. Call this.a to get the value of a in this.c{}

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

Then this example defines var that = this in advance for him, which is equivalent to storing this in the that variable. At this time, using that.a in the callback function is equivalent to using this in the function.

  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 has newly introduced an arrow function. In the arrow function, this points to the context object, so there is no need to write var that=this.

The es6 arrow function does not have its own this. The this in the
es6 arrow function is the this of the outer code block

Guess you like

Origin blog.csdn.net/weixin_45811256/article/details/109840936