search

Home  >  Q&A  >  body text

javascript - Why is this assigned to a variable here?

draw_anim:function(context){
                var me=this;
                var width = me.canvas.width,height = me.canvas.height;    
                
                    
                var img = new Image();
                img.src = this.imgsrcList[me.current];
                img.onload = function () { 
                        context.clearRect(0,0,width,height);
                        context.drawImage(img, 0, 0,img.width, img.height);
                }

What's good? Can't it be used directly?

过去多啦不再A梦过去多啦不再A梦2804 days ago512

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-05-18 10:50:59

    Generally speaking, this situation may be because this is called in some subsequent functions that do not belong to the current environment (such as click events). As for saving this as a temporary variable, I am not sure whether there is any performance optimization effect

    For example:
    img.onload = function () {

        context.clearRect(0,0,width,height);
        context.drawImage(img, 0, 0,img.width, img.height);
        //你这里想调用上面的this的话就需要用到me,因为这里的this指向的是img

    }

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-18 10:50:59

    Scope issue! me=this represents the current point of this. If this is written below, it may point to a different object. me can be used as a variable to receive this that appears this time and can be used in other functions. If you continue to use this, this this may point to Other objects, or undefined! It is recommended to take a look at this pointer and scope!

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-18 10:50:59

    O(∩_∩)O haha~ I am also a newbie, please forgive me if there are any mistakes
    First of all, your code is a section intercepted from a large object. Since you did not give this large object, let me make an assumption
    var animit={

    draw_anim:function(context){
                var me=this;
                var width = me.canvas.width,height = me.canvas.height;    
                
                    
                var img = new Image();
                img.src = this.imgsrcList[me.current];
                img.onload = function () { 
                        context.clearRect(0,0,width,height);
                        context.drawImage(img, 0, 0,img.width, img.height);
                }

    At this time, you enter the draw_anim method of the object. At this time, this is assigned to the variable me. The me below in this method represents the large object animit. This is done to avoid confusion with this in events such as p.onclick or timer events in the draw_anim method. That is to say, when you output this in the function of p.onclick operation, it refers to p, and Not a large object animit.

    reply
    0
  • Cancelreply