折腾:
期间,想要知道两个变量分别是什么类型的
结果发现用了:
<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
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 && results.length > 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), <anonymous>:179:63) at Object.InputMoment._this.handleSave [as click] (eval at <anonymous> (bundle_985deed87e62871e7f57.js:8103), <anonymous>:62:43) at HTMLButtonElement.eventProxy (eval at <anonymous> (bundle_985deed87e62871e7f57.js:834), <anonymous>:96:32) </code>
不想用instanceof
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中如何查看到当前对象变量的类名