Skip to content

if first line in constructor is 'somestring', "this" is called before calling super() in constructor #6901

Closed
@Mischi

Description

@Mischi

Hi,

we have experienced a problem where this is called before super() in a constructor function. This happen if the first line in a constructor is a string (for e.g ngInject;)

Typescript

class A  {
    blub = 6;
}


class B extends A {

  blub = 12;

  constructor() {
    'someStringForEgngInject';
    super()
  }
}

console.log(new B().blub);

and here the transpiled output

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
    function A() {
        this.blub = 6;
    }
    return A;
})();
var B = (function (_super) {
    __extends(B, _super);
    function B() {
        'someStringForEgngInject';
        this.blub = 12;
        _super.call(this);
    }
    return B;
})(A);
console.log(new B().blub);

The transpiled output with 'someStringForEgngInject' removed works correct.

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
    function A() {
        this.blub = 6;
    }
    return A;
})();
var B = (function (_super) {
    __extends(B, _super);
    function B() {
        _super.call(this);
        this.blub = 12;
    }
    return B;
})(A);
console.log(new B().blub);

We are using Typescript 1.7.5 and compile to ES6 which is handed of to Babel which will print a error message like this

Module build failed: SyntaxError: C:/dev/a.js: 'this' is not allowed before super()

The code for transpiling constructors probably "assumes" that the first line is always the "super" call and insert all default values in the second line?!

Issue found by @loxy, CC'ing @davidreher

Cheers,
Fabian

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFixedA PR has been merged for this issueHigh Priority

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions