覆盖函数的toString函数

Tân*_*Tân 3 javascript

我想通过答案生成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);
});
Run Code Online (Sandbox Code Playgroud)

现在,我想把它付诸实践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;
};
Run Code Online (Sandbox Code Playgroud)

未捕获的TypeError:无法读取未定义的属性'toString' console.log(GUID.NewGuid().toString());

我想要实现的目标:使用语法GUID.NewGuid().toString()生成id.

怎么解决?

Nin*_*olz 5

你需要一个类的实例.

var guid = new GUID.NewGuid;
Run Code Online (Sandbox Code Playgroud)

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());
Run Code Online (Sandbox Code Playgroud)