I'm learning javascript and I came across this situation, that I am not able to figure out by myself.
Let's say I created a constructor function like this which is trying to mimic an array:
// constructor function
function myArray() {
for (let i = 0; i < arguments.length; i++) {
this[`${i}`] = arguments[i];
}
this.length = arguments.length;
}
let fruits = new myArray('apple', 'mangoes', 'banana');
This will create Object fruits like this:
myArray {0: "apple", 1: "mangoes", 2: "banana", length: 3}
0: "apple"
1: "mangoes"
2: "banana"
length: 3
Now, I want to create my own function for myArray that can access all the values of the fruits object so I can perform some operations with it. Like, reverse function for example:
myArray.prototype.reverse = function () {
//how do i access all elements/values of friuts here?
};
I can set this.args = arguments; inside the constructor function
and access args inside the prototype function to do something with it.
But it is only limited to the original Object. If I add more elements to my object in the future by using another function, then it won't work as it is only taking args from the original object. Is there a way to pass the current Object inside the prototype function?
EDIT:
As Tushar Shahi mentioned, we can implement reverse function by reversing the original argument. But how can we access the elements that are added to the object later. Here is the full code just so you guys can have a clear understanding.
// constructor function
function myArray() {
this.args = Array.from(arguments);
for (let i = 0; i < arguments.length; i++) {
this[`${i}`] = arguments[i];
}
this.length = arguments.length;
}
let fruits = new myArray("apple", "mangoes", "banana");
// reverse function
myArray.prototype.reverse = function () {
// reversing the arguments first then assigning values
this.args = this.args.reverse();
for (let i = 0; i < this.args.length; i++) {
this[i] = this.args[i];
}
// but how do i access all elements/values of friuts here and not just the arguments?
}
// add/push function
myArray.prototype.add = function (a) {
let index = this.length;
this[index] = a;
this.length++;
}
// pop function
myArray.prototype.pop = function (a) {
let index = this.length - 1;
delete this[index];
this.length--;
}
fruits.add("orange"); // orange is added to fruits
fruits.add("pineapple"); // pineapple is added to fruits
console.log('fruits.reverse() ...', fruits.reverse());
console.log({ fruits }); // myArray {0: "banana", 1: "mangoes", 2: "apple", 3: "orange", 4: "pineapple", args: Array(3), length: 5}
.as-console-wrapper { min-height: 100%!important; top: 0; }
As you can see in the last console.log, I am able to reverse only 3 arguments that were passed originally but not the elements that were added later.
Pineapple should be the first fruit after reversing. So the question is
How can we access elements added later inside the reverse function? or
How can we access the current fruit object inside the reverse function?