You may define your own method for prototype:
// also you may use Object.defineProperty
Array.prototype.len = function() {
return this.length // --> this will be an array
}
and then call the function
[1, 2, 3].len()
BUT
It is a bad practice to define any new function in built-in prototypes - you can accidentally redefine existing method or method with the same name will be added in the future and it will cause unpredictable behavior.
Better approach either create your own prototype and use it
function MyArray () {
// your code
}
MyArray.prototype = Object.create(Array.prototype) // inheritance
MyArray.prototype.len = function () {
return this.length
}
or just create simple function and pass an array as an argument to it or as this
:
as argument:
function len (array) {
return array.len
}
as this
:
function len() {
return this.len
}
// invoking function
len.call(array)