Typescript “this” inside a class method

前端 未结 7 1436
温柔的废话
温柔的废话 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:12

    Very late to the party, but I think it is very important for future visitors of this question to consider the following:

    The other answers, including the accepted one, miss a crucial point:

    myFunction() { ... }
    

    and

    myFunction = () => { ... }
    

    are not the same thing "with the exception that the latter captures this".

    The first syntax creates a method on the prototype, while the second syntax creates a property on the object whos value is a function (that also happens to capture this). You can see this clearly in the transpiled JavaScript.

    To be complete:

    myFunction = function() { ... }
    

    would be the same als the second syntax, but without the capturing.

    So, using the arrow syntax in most cases will fix your problem of binding to the object, but it's not the same and there are many situations where you do want to have a proper function on the prototype in stead of a property.

    In these cases using a proxy or .bind() actually is the correct solution. (Although suffering readability.)

    More reading here (not primarily about TypeScript, but the principles stand):

    https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1

    https://ponyfoo.com/articles/binding-methods-to-class-instance-objects

提交回复
热议问题