Can one rename a built in JavaScript function?
I am trying to rename the "reverse" function to another name, but still have it do the same function
You can change the name by creating an alias in the prototype for the function
Array.prototype.newreversename = Array.prototype.reverse; var arr=["abc","sssd"]; console.log(arr.newreversename())
You can also create a wrapper function for the new function
Array.prototype.newreversefunction = function() { return this.reverse(); }; var arr=["a","c"]; console.log(arr.newreversefunction())
This is called monkey patching. Javascript is flexible enough to allow you to change fundamental things like this, but you will break other code and make your own code unreadable by others if you modify normal parts of the language this way.
Array.prototype.rev = Array.prototype.reverse
> function reverse() { [native code] }
Array.prototype.reverse = null
> null
[1,2,3,4,5].rev()
> [5, 4, 3, 2, 1]
[1,2,3,4,5].reverse()
> "[1,2,3,4,5].reverse is not a function"
You can , but I would strongly recommend against doing so.
The proper way to do it would be to get the property descriptor for the method from the prototype ( Object.getOwnPropertyDescriptor
), then use that to define a new property ( Object.defineProperty
), and use delete
to get rid of the previous one:
Object.defineProperty( Array.prototype, "thingy", Object.getOwnPropertyDescriptor(Array.prototype, "reverse") ); delete Array.prototype.reverse; console.log([1,2,3].thingy()); // [3, 2, 1] console.log([1,2,3].reverse()); // Error
You can do it like this:
Array.prototype.myReverse = Array.prototype.reverse;
delete Array.prototype.reverse;
But you should avoid this, as many libraries rely on the reverse function. Instead, if you want to call it using another name, just do the first line:
Array.prototype.myReverse = Array.prototype.reverse;
You can change the name by creating an alias
Array.prototype.slicing = Array.prototype.slice; var animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slicing(2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.