Basics

Challenges

Classes

Cookies

Debugging

Events

External Files

Flow Control

Forms

Functions

Html Elements

Installation

Interfaces

Keywords

Modules

Namespaces

Operators

Reference Files

String

Types

TypeScript - Function as Class Property

You can also have a Property which its Type is a Function... or more accurately, gets it value from an anonymous function.


namespace ClientSideToolBox.ObjectTypes
{
    var spaceship =
    {
        ShipType: "Cruiser",
        TotalCrew: 50,
        Weight: 250000,
CalculateSpeed: function () { return (this.TotalCrew + this.Weight) * 2; }
    };

    console.log("Speed: " + spaceship.CalculateSpeed());
}

 

Here is the same example except the function (properties) now accepts an argument which is a number and uses that as the multiplier.


var spaceship =
{
    ShipType: "Cruiser",
    TotalCrew: 50,
    Weight: 250000,
    CalculateSpeed: function (x : number) { return (this.TotalCrew + this.Weight) * x; }
};
console.log("Speed: " + spaceship.CalculateSpeed(7));