Javascript prototype: possible to change reference object value?

2

EDIT: Normally it is in the end, but the question was poorly formulated and I decided to switch to this example, which is much better. Here is an example of a function that does nothing as an Array method:

Array.prototype.nada = function () {
    var In = this;
    var Out = new Array();
    for (var i=0; In.length>0; i++) { Out.push(In.pop()); }
    In = Out;   
    console.log("Resultado interno: ");
    console.log(Out);   
}

To test ...

function testeNada() {
    var Nada = ["Eu","Você","Nós"];
    Nada.nada();
    console.log("Resultado de Nada: ");
    console.log(Nada);
}

In Safari, the inner Out result is the same Array as the Start (Nothing) and the Nothing test result is an empty Array!

In the case of prototypes preexisting methods, it works like this:

var UmaArray = new Array();
UmaArray.push("umValor"); // UmaArray já é ["umValor"]

By logic, I would do so:

Array.prototype.empurre = function(valor){
 Arr = this;
 Arr.push(valor);
 this = Arr; // Aqui dá erro ReferenceError: Left side of assignment is not a reference
}
var UmaArray = new Array();
UmaArray.empurre("umValor"); // Sonho de ver UmaArray ser ["umValor"]

That is, you can not modify yourself.

As already mentioned in the comments below, taking this = Arr method works. So I rephrase the question: is there any way to actually change the reference object by just applying methods on it myself?

    
asked by anonymous 14.12.2016 / 02:00

2 answers

2

You have two ways to do this:

If you use this directly you will be changing the ref obj.

Array.prototype.empurre = function(valor){
    this.push(valor);
};
var UmaArray = new Array();
UmaArray.empurre("umValor");

The second way is similar to the rotate implementation

Array.prototype.empurre = function(valor){
    var push = Array.prototype.push;
    push.apply(this, [valor]);
};
var UmaArray = new Array();
UmaArray.empurre("umValor");
    
14.12.2016 / 02:42
1
The reason why the first example returns [] is because In is a pointer of this and at each iteration of the loop you are doing In.pop() .

To change the array itself you can do this:

Array.prototype.inverter = function() {
    for (let i = 0, l = this.length; i < l; i++) {
        this[i] = this[i].split('').reverse().join('');
    }
}
var array = ["Eu", "Você", "Nós"];
array.inverter();
console.log("Resultado de Nada: ");
console.log(array); // ["uE", "êcoV", "sóN"]

Basically, methods that change this do what you asked for. All Array methods that change the original object (such as .pop() , .shift() , etc) change this within that function added to prototype . p>     

15.12.2016 / 23:07