Reputation: 371
If I do:
!isNaN('2') && parseInt('2').toString() === '2' // returns 'true'
I have the following JavaScript function:
String.prototype.isDigit = function() {
return !isNaN(this) && parseInt(this).toString() === this ? true : false;
}
However:
'2'.isDigit() // returns 'false'
Furthermore,
String.prototype.isDigit = function() {
return this === '2' ? true : false;
}
'2'.isDigit() // returns 'false'
What is the discrepancy here? Shouldn't this === '2'
?
Upvotes: 4
Views: 124
Reputation: 707218
In your .isDigit()
method, this
is a String object (not a string primitive) and ===
with an object is only true if the two operands are exactly the same object, not just two separate objects with the same value or not with one an object and another a primitive.
So, in your method:
String.prototype.isDigit = function() {
console.log(typeof parseInt(this).toString()); // "string"
console.log(typeof this); // "object"
return !isNaN(this) && parseInt(this).toString() === this ? true : false;
}
And, ===
will never be true for two operands that are different types.
You can stay with your approach, but use .valueOf()
to get the primitive because comparing two string primitives with ===
just compares their values:
String.prototype.isDigit = function() {
return !isNaN(this) && parseInt(this).toString() === this.valueOf();
}
Upvotes: 2
Reputation: 83
Try opening up the console and doing:
String.prototype.this = function() { return this; };
"2".this();
You'll see "this" is an object.
Upvotes: 1
Reputation: 60527
Shouldn't this === '2' ?
No, actually. In this case, this
is actually an instance of String
, which is different from the string primitive '2'
. this
is essentially equal to new String('2')
, and each instance of such an object is unique.
You could cast it to a string primitive though.
String.prototype.isDigit = function() {
var that = '' + this;
return !isNaN(that) && parseInt(that).toString() === that ? true : false;
}
'2'.isDigit();
Upvotes: 7