3

How can I inherit from a constructor function in javascript?

e.g. I have a base class written in native js

var MyModule;
(function (MyModule) {
    var MyBase = (function () {

        function MyBase(container, $MyElement) {

            this._container = container;
            this._$MyElement = $MyElement;
        }


        MyBase.prototype.toString = function () {
            return this._previewType;
        };

        MyBase.prototype.method1 = function(){

        };

        MyBase.prototype.method2 = function () {
            return this._isPreviewAffected;
        };



        return MyBase;
    })();
    MyModule.MyBase = MyBase;    
})(MyModule || (MyModule = {}));

How do I inherit it in typescript. I tried following code. I get the error "Incorrect reference: referenced file: "my-base.js" cannot be resolved"

 /// <reference path="my-base.js" />

    module MyModule {

        export class MyConcrete extends MyBase {

        }

    }
1
  • 3
    What do you mean by - "did not work"? Commented May 30, 2013 at 12:00

1 Answer 1

4

You need to declare the signature equivalent of your javascript code in typescript. This is to let TypeScript know what your JavaScript means if it was written in TypeScript:

declare module MyModule{
    export class MyBase{
        constructor(container, $MyElement);
        toString();
        method1():void;
        method2():bool;
    }
}

module MyModule {    
        export class MyConcrete extends MyBase {    
        }    
    }

Additionally /// <reference path="file" /> is for Typescript files only. For Javascript files you can use some script management (e.g. <script> tags, requireJS etc) to ensure MyBase is available before MyConcrete.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.