Last active
September 19, 2020 13:16
-
-
Save saipraveen-a/628da3854223dc743e6c56198090948f to your computer and use it in GitHub Desktop.
JavaScript Understanding the Weird Parts - Built-In Function Constructors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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