最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeScript Class Inheritance: 'super' Can Only Be Referenced in Members of Derived Classes or Objec

programmeradmin0浏览0评论

We're using TypeScript classes with inheritance and have run into an apparent scoping issue. TypeScript/JavaScript is not allowing us to call 'super' from within a promise structure (or even from an enclosed function). We're receiving this error:

TypeScript: 'super' Can Only Be Referenced in Members of Derived Classes or Object Literal Expressions

Is there a way around this? Here's the code:

export class VendorBill extends Transaction {
    constructor() {
        super();
    }

    save() {

        let deferred = $.Deferred();

        $.ajax({
            type: "GET",
            url: '/myrestapi',
            success: function (data) {    
                deferred.resolve();    
            },
            error: function (jqXHR: any, textStatus, errorThrown) {
                deferred.reject()
            }
        })

        $.when(deferred).always(function () {
            super.save();  <----------- THIS IS CAUSING THE ERROR
        })    
    }
}

We're using TypeScript classes with inheritance and have run into an apparent scoping issue. TypeScript/JavaScript is not allowing us to call 'super' from within a promise structure (or even from an enclosed function). We're receiving this error:

TypeScript: 'super' Can Only Be Referenced in Members of Derived Classes or Object Literal Expressions

Is there a way around this? Here's the code:

export class VendorBill extends Transaction {
    constructor() {
        super();
    }

    save() {

        let deferred = $.Deferred();

        $.ajax({
            type: "GET",
            url: '/myrestapi',
            success: function (data) {    
                deferred.resolve();    
            },
            error: function (jqXHR: any, textStatus, errorThrown) {
                deferred.reject()
            }
        })

        $.when(deferred).always(function () {
            super.save();  <----------- THIS IS CAUSING THE ERROR
        })    
    }
}
Share Improve this question asked Feb 10, 2017 at 22:22 A2MetalCoreA2MetalCore 1,6394 gold badges27 silver badges50 bronze badges 1
  • Also worth pointing out you're using the promise antipattern of using an extra deferred object when you don't need one. You can just do $.ajax({...}).always(() => { super.save(); }); – Adam Jenkins Commented Feb 10, 2017 at 22:38
Add a ment  | 

1 Answer 1

Reset to default 5

The reason is that the piler turns super.save() to:

_super.prototype.fn.call(this);

But this isn't the right one because you're passing a function which isn't bound to the right context.

You can use an arrow function:

$.when(deferred).always(() => {
    super.save();
}) 

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论