JavaScript instanceof 和 moment.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31921026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:34:34  来源:igfitidea点击:

JavaScript instanceof and moment.js

javascriptmomentjs

提问by Some User

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).

我试图理解 JavaScript 世界中的类型。我的页面正在使用moment.js。我有一个功能,有时会返回一个moment()等次,返回string(它的遗留代码狂野)。

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 instanceofor moment?

当我执行上面的代码时,我从来没有得到we have a moment.. 即使我手动设置 set result = moment();。这是为什么?是我误会了instanceof还是moment

回答by FreeLightman

Moment version 2.13.0

时刻版本 2.13.0

There is a static method .isMoment:

有一个静态方法.isMoment

enter image description here

在此处输入图片说明

回答by Ginden

First of all, instanceofisn't perfectly reliable.

首先,instanceof不是完全可靠的。

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

其次,moment()返回Moment未向用户公开的类的实例。下面的代码证明了这一点:

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

Third of all, momentprovide function moment.isMomentthat will solve your problem.

第三,moment提供moment.isMoment可以解决您问题的功能。

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

最后但并非最不重要的 - 您的代码应该使用一致的返回类型 - 始终返回moment实例或始终返回字符串。它会减少你未来的痛苦。

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

您可以moment通过调用momentfunction - moment(string)equals in value来确保您始终拥有实例moment(moment(string)),因此您可以始终将参数转换为moment实例。