Skip to content

Instantly share code, notes, and snippets.

@saipraveen-a
Last active September 19, 2020 13:16
Show Gist options
  • Save saipraveen-a/628da3854223dc743e6c56198090948f to your computer and use it in GitHub Desktop.
Save saipraveen-a/628da3854223dc743e6c56198090948f to your computer and use it in GitHub Desktop.
JavaScript Understanding the Weird Parts - Built-In Function Constructors
let a = new Number(3);
a;
a.toFixed(2);
Number.prototype.toFixed(2);
let b = new String('John');
b.indexOf('o');
String.prototype.indexOf('o');
"John".length // boxing; same as new String('John').length
let c = new Date('12/31/2020');
//Add some functionality to all Strings.
String.prototype.isLengthGreaterThan = function(limit) {
return this.length > limit;
// the this reference will be handled dynamically based on the object on which the function is invoked.
}
console.log(new String('Some String').isLengthGreaterThan(10));
console.log("John".isLengthGreaterThan(3));
// Many Libraries and frameworks use this feature of Javascript
Number.prototype.isPositive = function() {
return this > 0;
}
console.log(3.isPositive()); // this fails as the boxing does not work for all types.
var num = new Number(3);
console.log(num.isPositive());
// Using built-in function constructors for primitives is a little dangerous as we get an object and not a primitive
// For dealing with Dates, use Moment.js library
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment