我想通过 the answer 生成一个 GUID 字符串.
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
现在,我想将它放入 toString
函数中,例如:GUID.NewGuid().toString()
。
我试过了(没用):
let GUID = function () {};
GUID.NewGuid = function () {};
GUID.NewGuid.prototype.toString = function () {
let guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
return guid;
};
Uncaught TypeError: Cannot read property 'toString' of undefined
console.log(GUID.NewGuid().toString());
我想要实现的目标:使用语法 GUID.NewGuid().toString()
生成一个 id。
如何解决?
最佳答案
你需要一个 instance类(class)的。
var guid = new GUID.NewGuid;
let GUID = function () {};
GUID.NewGuid = function () {};
GUID.NewGuid.prototype.toString = function () {
let guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
return guid;
};
var guid = new GUID.NewGuid;
console.log(guid.toString());
关于javascript - 覆盖函数的 toString 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40083557/