Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  199] [ 3]  / answers: 1 / hits: 21746  / 9 Years ago, mon, august 10, 2015, 12:00:00

I'm attempting to understand types in the JavaScript world. My page is using moment.js. I have a function that sometimes returns a moment() and other times, returns a string (it's legacy code gone wild).



My code kind of looks like this:



var now = getDate();
if (now instanceof moment) {
console.log('we have a moment.');
} else {
console.log('we have a string.');
}


function getDate() {
var result = null;
// Sometimes result will be a moment(), other times, result will be a string.
result = moment();
return result;
}


When I execute the code above, I never get we have a moment.. Even if I manually make set result = moment();. Why is that? Am I misunderstanding instanceof or moment?


More From » momentjs

 Answers
21

First of all, instanceof isn't perfectly reliable.



Second of all, moment() returns instance of Moment class that isn't exposed to user. Following code prove this:



moment().__proto__.constructor // function Moment()
moment().constructor === moment; // false


Third of all, moment provide function moment.isMoment that will solve your problem.



And last, but not least - your code should use consistent return types - always return moment instances or always return strings. It will reduce your pain in future.



You can ensure that you always have moment instance by calling moment function - moment(string) equals in value moment(moment(string)), so you can just always convert your argument to moment instance.


[#65468] Friday, August 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;