With TypeScript: unable to refer to 'this' (class) from inside a function

前端 未结 3 1279
猫巷女王i
猫巷女王i 2020-12-21 05:50

I\'m learning TypeScript and have the following class:

class DetailDriver {

    public get driver() {
        return super.getEntity();
    }

         


        
相关标签:
3条回答
  • 2020-12-21 06:22

    For reference, you could also just do:

    class SomeClass {
    
        public someMethod() {
            // Do something
        }
        public anotherMethod() {
            var that = this; // Reference the class instance
    
            function someFunction () {
                that.someMethod();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-21 06:31

    Well,

    According to section 4.9.2 of the TypeScript Language Specification you should use fat arrow syntax to preserve the scoping for this.

    return promise
            .then(() => return.this.id;)
            .fail(somethingWrong);
    

    Then the this keyword is properly determined to be a Driver.

    0 讨论(0)
  • 2020-12-21 06:35

    You could refactor to something like this:

    class DetailDriver {
    
        public get driver() {
            return super.getEntity();
        }
    
        public activate(): breeze.Promise {
            var id = this.driver.id(); // this refers to (class) DetailDriver
    
            return promise
                .then(this.getCertificate.bind(this)) // <- important part
                .fail(somethingWrong);
        }
    
        // new method function here
        private getCertificate() {
            var id = this.driver.id(); // this refers to any
            return ...
        }
    }
    

    Using the function keyword anywhere in your class will make any reference to this keyword refer to that function rather than the outer class. Generally, you want to avoid defining functions inside of classes, unless you use the "fat arrow" syntax. That would look like this:

    class DetailDriver {
    
        public get driver() {
            return super.getEntity();
        }
    
        public activate(): breeze.Promise {
            var id = this.driver.id(); // this refers to (class) DetailDriver
    
            return promise
                .then(() => { // <- important part
                    var id = this.driver.id(); // this refers to any
                    return ...
                })
                .fail(somethingWrong);
        }
    }
    
    0 讨论(0)
提交回复
热议问题