Thursday, May 16, 2013

JavaScript Learning #5 - Extending Built-In Objects with Prototype

Prototype can also be used to extend JavaScript's built-in objects.
The displayed code uses an anonymous function to add the negate property to JavaScript's Number type; the new property reverses the sign of any numeric value.

Example:


var myValue = 345.62;

Number.prototype.negate = function() {
return -1* this;
};
console.log(myValue.negate());

Number.prototype.half = function() {
return this/2;
};

console.log(myValue.half());


Output:
-345.62

172.81

No comments:

Post a Comment