Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding toString function of a function

Tags:

javascript

I want to generate a GUID string via the answer.

'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);
});

Now, I want to put it into toString function, like: GUID.NewGuid().toString().

I've tried (not working):

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());

What I want to achieve: using syntax GUID.NewGuid().toString() to generate an id.

How to fix it?

like image 309
Tân Avatar asked Mar 05 '26 17:03

Tân


1 Answers

You need an instance of the 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());
like image 94
Nina Scholz Avatar answered Mar 08 '26 06:03

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!