If you want to define your own method for prototype, there are a few different approaches you can take:
// You could use Object.defineProperty as well
Array.prototype.len = function() {
return this.length // --> this will be an array
}
After defining the method, you can call it like this:
[1, 2, 3].len()
However,
It's generally considered bad practice to add new functions to built-in prototypes because it can lead to issues such as accidentally redefining existing methods or conflicting with future updates. A better approach would be to create your own prototype and use that instead.
function MyArray () {
// Your code here
}
MyArray.prototype = Object.create(Array.prototype) // Inheritance
MyArray.prototype.len = function () {
return this.length
}
Alternatively, you could simply create a standalone function and pass the array as an argument or use it as this
:
Passing the array as an argument:
function len (array) {
return array.len
}
Using this
:
function len() {
return this.len
}
// Invoking the function
len.call(array)