Typescript “this” inside a class method

前端 未结 7 1391
温柔的废话
温柔的废话 2020-11-30 02:45

I know this is probably painfully basic, but i am having a tough time wrapping my head around it.

class Main
{
     constructor()
     {
         requestAni         


        
相关标签:
7条回答
  • 2020-11-30 03:27

    In short, the this keyword always has a reference to the object that called the function.

    In Javascript, since functions are just variables, you can pass them around.

    Example:

    var x = {
       localvar: 5, 
       test: function(){
          alert(this.localvar);
       }
    };
    
    x.test() // outputs 5
    
    var y;
    y.somemethod = x.test; // assign the function test from x to the 'property' somemethod on y
    y.test();              // outputs undefined, this now points to y and y has no localvar
    
    y.localvar = "super dooper string";
    y.test();              // outputs super dooper string
    

    When you do the following with jQuery:

    $.proxy(this.update, this);
    

    What you are doing is overriding that context. Behind the scenes jQuery will guive you this:

    $.proxy = function(fnc, scope){
      return function(){
         return fnc.apply(scope);  // apply is a method on a function that calls that function with a given this value
      }
    };
    
    0 讨论(0)
提交回复
热议问题