Extending the functionality of the JavaScript base object in Typescript

Source: Internet
Author: User
Tags string format

In recent work, take note: Suppose we need a function, the output of a number such as 10000 to the following string format "10,000", generally write a method, then I would like to more convenient, directly add a format method to the # type, For example, a method called Toformat to implement a formatted string.

Add a. D.ts definition

The method to extend a base object in typescript requires that the compiler have this method in advance:

1 interface Number {2    Toformat (): string; 3 }
Add implementation

The specific implementation can be written as needed, and it is important to note that the prototype object is added to the line:

1Number.property.toFormat =function () {2     //get the value of the number, i.e. the number itself3     varValue = This. ValueOf ();4     //here is the specific handling code, which is skipped here5     varstr = "Code";6     //return and then7     returnstr;8}

You can call it directly:

1 var i = 10000; 2 Console.log (I.toformat ());

My implementation here is written in JavaScript, and if it is in typescript, it can be written using TS.

Extending the functionality of the JavaScript base object in Typescript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.