javascript - 覆盖函数的 toString 函数

标签 javascript

我想通过 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/

相关文章:

javascript - 来自卸载事件 : how to ensure user sees most up-to-date information from DB on next page load 的同步 AJAX 发布

javascript - 简单 HTML 表单创建循环中的永恒循环

javascript - 从 'this' 中使用 jquery 查找最近的元素

javascript - jQuery live 不工作

javascript - 编写带有回调的函数

javascript - 如何更改 extjs 中特定列中的所有值?

javascript - protobuf.js : print int64 Object as string in node. js

javascript - 只能输入数字 9 < 37

javascript - RiotJS - 如何使用 Observable 模式在子标签之间传递事件?

javascript - PHP Xpath JS 如何用 JS 从网站获取内容?