Sasha
Sasha

Reputation: 1570

Unable to instantiate typescript class in javascript

I am sorry for potentially damn question.

Problem:

I've got the class defined in typescript as so:

1    class MyClass {
2        constructor() {
3            alert("MyClass instantiated!");
4        }
5    }
6    export = MyClass;

It's compiled into javascript as follows:

1    var MyClass = (function () {
2        function MyClass() {
3            var _this = this;
4            alert("MyClass instantiated!"); 
5        }
6    }
7    module.exports = MyClass

It is referenced from the jsp page - which also does the following:

<script language='javascript' src="myclass.js">
    var myclass = new MyClass();
</script>

Now, I've debugged it and it hits the line 1 (of compiled .js) and then exits at line number 7 of the same file.

Question:

Why doesn't it go in the function and exits? Am I instantiating it wrongly?

Upvotes: 2

Views: 983

Answers (2)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19130

The problem is that you exported the TypeScript into a commonjs format (indicated by the module.exports = MyClass at line 7).
What you need is to compile the TypeScript into an UMD format, which can be accepted by the browser.
Or simply remove export = MyClass; from TypeScript source.


The working TS code:

class MyClass {
    constructor() {
        alert("MyClass instantiated!");
    }
}

will be compiled to:

var MyClass = (function () {
    function MyClass() {
        var _this = this;
        alert("MyClass instantiated!"); 
    }
}

Then use it on the page:

<script type="text/javascript" src="myclass.js"></script>
<script>
    var myclass = new MyClass();
</script>

Upvotes: 2

Naftali
Naftali

Reputation: 146350

You can't put context into a script tag that is loading another file.

Try this instead:

<script src="myclass.js"></script>
<script>
    var myclass = new MyClass();
</script>

Upvotes: 0

Related Questions