JavaScript Learning Notes: Extending the functionality of a type

Source: Internet
Author: User

JavaScript is allowed for basic types of expansion functionality. For example, you can make this method available to all objects by adding a method to Object.prototype. Such a way applies to functions, arrays, strings, numbers, regular expressions, and Boolean values.

For example, all functions can be available by adding methods to the Function.prototype:

function (Name, func) {  this. Prototype[name] = func;    return  This ;  }

By adding method methods to Function.prototype, then adding methods to call the Mehod method directly, without having to write prototype. For example, JavaScript does not have an shaping type, and we can add an integer method class implementation to Number.prototype.

function () {    return math[ this < 0? ' Ceil ': "Floor"(this);}); Console.log (( -10/3). Integer ());   Out Put-3

By adding methods to basic types, the expressive force of language can be greatly improved. Because of the dynamic nature of JavaScript archetype inheritance, new methods are immediately assigned to all object instances, including objects that were created before the method was added.

Because primitive types are common constructs, be careful when using class libraries. An insurance policy is to add it only when you are sure that the method is not there, for example:

function (Name, func) {  if (!  this. prototype (name)) {    this. Prototype[name] = func;  }    return  This ;};

JavaScript Learning Notes: Extending the functionality of a type

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.