在学习mongoDB时,我注意到一个构造函数返回带有原型函数的字符串。例如
以下代码将生成一个随机字符串,字符串中的前4个字母包含时间戳,并获取具有原型功能的时间戳。
const id = new ObjectID() // 5c8766f4bcd712911ab81eea
console.log(id.getTimestamp()) // will print the date
我只是在努力完成它。我试图以相同的方式创建简单的构造函数,但它总是返回对象。我们如何使它返回单个值而不是带有原型函数的对象。
function getMyTime(){
this.timestamp = new Date().getTime()
}
const timestamp = new getMyTime(); // should print timestamp 1552385374255
console.log(timestamp.printReadableDate()) // should print date Tue Mar 12 2019 15:39:34 GMT+0530 (India Standard Time)
已编辑
class GetTime {
constructor(){
this.time = new Date().getTime();
}
getActualDate(){
}
toString(){
return this.time
}
}
const stamp = new GetTime();
console.log(stamp) // should be 1552472230797
console.log(stamp.getActualDate()) //should be Wed Mar 13 2019 15:47:10 GMT+0530 (India Standard Time)
在ObjectId
由使用的MongoDB类是最终ObjectId
提供类JS-BSON。此类ObjectId
使用Node.js提供的功能util.inspect
将自身打印为字符串:
ObjectId.prototype[util.inspect.custom || 'inspect'] = ObjectId.prototype.toString;
发生的事情是js-bson
添加了一个名称为util.inspect.custom
或的方法"inspect"
。第二个名称用于与Node 6.6.0之前的Node版本兼容。在节点,console.log
用途util.format
,最终使用util.inspect
,以确定如何打印传递给每一个对象console.log
,并且可以自定义什么util.inspect
做的,我们要自定义的对象添加一个方法。对于6.6.0之前的Node版本,必须命名该方法"inspect"
,对于更高的版本,该名称必须具有的值util.inspect.custom
。
因此,您可以从内容中抽出一页,js-bson
并使用以下方法实现您的课程:
const util = require("util");
class GetTime {
constructor(){
this.time = new Date().getTime();
}
toString() {
return this.time;
}
}
GetTime.prototype[util.inspect.custom || 'inspect'] = GetTime.prototype.toString
const stamp = new GetTime();
console.log(stamp);
或者,此语法可能对您或您使用的开发工具更可口。过去,我曾经使用过一些代码文档工具,这些工具绝对可以轻松地实现以下目的:
const util = require("util");
class GetTime {
constructor(){
this.time = new Date().getTime();
}
toString() {
return this.time;
}
[util.inspect.custom || "inspect"]() {
return this.toString();
}
}
const stamp = new GetTime();
console.log(stamp);
尽管有一个额外的调用,但此语法提供的结果与早期语法相同。
如上所述,此技巧仅在Node中有效。如果我尝试将ObjectId
对象传递给console.log
Chrome,那么Chrome会对其他所有对象执行相同的操作:打印构造函数名称和对象的字段。据我所知,没有跨平台的方法可以自定义console.log
打印对象的方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句