JavaScript instanceof和moment.js [英] JavaScript instanceof and moment.js
问题描述
我试图了解JavaScript世界中的类型.我的页面正在使用 moment.js .我有一个函数,有时返回一个moment()
,有时返回一个string
(它的遗留代码变得疯狂了).
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;
}
当我执行上面的代码时,我从没得到we have a moment.
.即使我手动进行设置result = moment();
.这是为什么?我是误解了instanceof
还是moment
?
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
?
推荐答案
首先,instanceof
并不是十分可靠.
First of all, instanceof
isn't perfectly reliable.
所有第二个,moment()
返回未公开给用户的Moment
类的实例.以下代码证明了这一点:
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
第三,moment
提供功能moment.isMoment
将解决您的问题.
Third of all, moment
provide function moment.isMoment
that will solve your problem.
最后,但并非最不重要的一点-您的代码应使用一致的返回类型-始终返回moment
实例或始终返回字符串.将来会减轻您的痛苦.
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.
您可以通过调用moment
函数来确保始终拥有moment
实例-moment(string)
等于值moment(moment(string))
,因此您始终可以将参数转换为moment
实例.
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.
这篇关于JavaScript instanceof和moment.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!