2
EDIT: It’s usually at the end, but the question was poorly worded and I decided to switch to this example that is much better. Follow the 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);
}
For testing...
function testeNada() {
var Nada = ["Eu","Você","Nós"];
Nada.nada();
console.log("Resultado de Nada: ");
console.log(Nada);
}
In Safari, the internal Out result is the same as the Start Array (Nothing) and the Nothing test result is an empty Array!
In the case of pre-existing prototype 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, it is not possible to modify oneself.
As already mentioned below in the comments, except this = Arr the method works. So I rephrase the question: is there any way to really change the reference object or just by applying methods to itself?
I don’t understand why you want to assign a value to
this
, even more than in your example this value is itself... If you take this line your code already works as you want.– bfavaretto
In fact, I don’t think I was happy with that question. I’ll withdraw. Thank you.
– Gustavo
I re-asked the whole question with a simpler and more direct example.
– Gustavo
Yet I still don’t understand what you’re trying to do! Your new example does exactly what I expected of it. There’s something that’s not clear to you, but I haven’t figured it out yet.
– bfavaretto
The first time I tried to explain why I came to this point. I take advantage of functions to create methods, but in the end you can not simply take the result and "stick" inside the object. The code will have to be modified as explained in picossi below. So I modified the question and left only the concept to others to look for with that kind of doubt. I have several methods that I will have to modify to have the object present the result at the end, is part!
– Gustavo