1

My typescript code:

export class File {
    isOpenEnabled() {
        return false;
    }

    openClicked() {
        debugger;
    }
}

define([], function () {
    return {
        handler: new File()
    };
});

Is turned into:

define(["require", "exports"], function(require, exports) {
    var File = (function () {
        function File() {
        }
        File.prototype.isOpenEnabled = function () {
            return false;
        };

        File.prototype.openClicked = function () {
            debugger;
        };
        return File;
    })();
    exports.File = File;

    define([], function () {
        return {
            handler: new File()
        };
    });
});

Why the insertion of prototype?

thanks - dave

2 Answers 2

2

Functions in javascript are objects.

For example:

function MyClass () {

  this.MyMethod= function () {};
}

Every time a new instance of MyClass is created, a new instance of MyMethod is also created. A better approach is to add the function MyMethod to the prototype of MyClass:

MyClass.prototype.MyMethod = function(){};

In this way no matter how many instances of MyClass you create, only a single MyMethod will be created.

Back to your question I think that typescript is doing exactly this kind of optimization for the methods that you defined in your File class.

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

1 Comment

So it creates MyClass.prototype once and it is then assigned to all instances of the MyClass object? Thanks - dave
1

There are two reason:

  • Memory optimization (already mentioned by Alberto)
  • Prototypical Inheritance

The second reason as well as the first is well covered in : http://javascript.crockford.com/inheritance.html

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.