vendredi 11 septembre 2015

Why String.Prototype replace doesn't work inside nested functions?

I have declared in same script file the following sub-string replace function :

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index + character.length);
}

If I use this function in the main script file (for example right after its declaration), it works properly with string output.

If I use this function inside nested functions, more exactly I have a function inside another function and I call "replaceAt" inside the second function, it doesn't work and it truncates all characters after the "index" specified in "replaceAt". I also specify that this is a content script in a Chrome extension.

Example (works okay outside functions, in main file) :

var h = '000000';
h = h.replaceAt(3, "1");
console.log(h);

Example (truncates everything after "index") :

function do_lut() {
    function nfu_change(e, i) {
        if (e.checked) {
            if (temp != null) {
                console.log(i + " - " + temp);
                temp = temp.replaceAt(i, "1");
            } else {
                temp = '000000000000000'.replaceAt(i, "1");
            }
        }
    }
}

Temp is just a string variable declared as empty global. Also, the above is not the full statement with event passing etc, just for exemplification.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire