最新消息:20190529 VPS服务器已从腾讯云香港换为Vultr新加坡,主题仍用朋友推荐的大前端D8

【未解决】js中如何查看到当前对象变量的类名

JS crifan 311浏览 0评论

折腾:

【已解决】js中如何把moment转换为Date对象

期间,想要知道两个变量分别是什么类型的

结果发现用了:

<code>console.log(`before select: this.state.selected_time=${this.state.selected_time}`);
console.log(`curMoment type=${typeof this.state.curMoment}`);
console.log(`selected_time type=${typeof this.state.selected_time}`);

this.setState({
isSelectTimeVisible: false,
selected_time: this.state.curMoment
});

console.log(`after select: this.state.selected_time=${this.state.selected_time}`);
console.log("curMoment type=", typeof this.state.curMoment);
console.log("selected_time type=", typeof this.state.selected_time);
</code>

打印出来的竟然都是object:

<code>saved Sat, Mar 24, 2018 10:16 AM
index.js?7207:128 before select: this.state.selected_time=null
index.js?7207:129 curMoment type=object
index.js?7207:130 selected_time type=object
index.js?7207:137 after select: this.state.selected_time=1521857763511
index.js?7207:138 curMoment type= object
index.js?7207:139 selected_time type= object
</code>

所以需要搞清楚,js中如何知道两个变量到底是哪个类的变量,类的名字是啥

js typeof object name

typeof – JavaScript | MDN

JavaScript Data Types

How do I get the name of an object’s type in JavaScript? – Stack Overflow

试试:

<code>Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results &amp;&amp; results.length &gt; 1) ? results[1] : "";
};
</code>

结果:

<code>console.log(`curMoment type name=${this.state.curMoment.getName()}`);
console.log(`selected_time type name=${this.state.selected_time.getName()}`);
</code>

失败:

<code>index.js?7207:131 Uncaught TypeError: this.state.curMoment.getName is not a function
    at CowActivity.onConfirmSelectTime (eval at 618 (0.35c4e307f4dd07c2843c.hot-update.js:7), &lt;anonymous&gt;:179:63)
    at Object.InputMoment._this.handleSave [as click] (eval at &lt;anonymous&gt; (bundle_985deed87e62871e7f57.js:8103), &lt;anonymous&gt;:62:43)
    at HTMLButtonElement.eventProxy (eval at &lt;anonymous&gt; (bundle_985deed87e62871e7f57.js:834), &lt;anonymous&gt;:96:32)
</code>

不想用instanceof

instanceof – JavaScript | MDN

oop – How to get a JavaScript object’s class? – Stack Overflow

去试试:

obj.constructor.name

console.log(`curMoment type name=${this.state.curMoment.constructor.name}`);

console.log(`selected_time type name=${this.state.selected_time.constructor.name}`);

结果:

Uncaught TypeError: Cannot read property ‘constructor’ of null

算了,放弃吧。

此处preact项目中,暂时还是找不到好的办法,可以在js中查看到变量(Date和moment)变量的类的名字。

转载请注明:在路上 » 【未解决】js中如何查看到当前对象变量的类名

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
62 queries in 0.114 seconds, using 18.84MB memory