So I understand that you can add new methods to your javascript object prototype.
myObject.prototype.myFunction = function {}. I wanted to do the same for my array instance but keep getting errors. Something like this.
var myArray = [1,2,3,4,5,6,7,8,9,0];
myArray.prototype.bubbleSort = function(){
// sort stuff here.
}
Why is this not allowed ? I thought since arrays inherit from Object you should be able to extend them the same way as objects.
If this is not possible how can I add a . notation function call to my arrays so I can say. myArray.bubbleSort(); instead of bubbleSort(myArray); without adding methods to Array.prototype.
I think my question caused some confusion so please read this section before answering. Thank you.
My goal is to have an array named myArray that has a specific method bubbleSort. I don't want to change the main Array.Prototype.
So later I can do something like this. var yourArray = new myArray() so now since yourArray is instance of myArray it will have access to bubblesort function.
Can we achieve this without changing the main Array.prototype ?
.prototype.bubbleSortmyArray.constructor.prototype.bubbleSort = function(){…};.myArray.bubbleSort = function() { ... };. Simple as that. Adding it to the prototype means it will be added to many instances.