简体   繁体   English

重命名内置 javascript 函数

[英]Renaming built in javascript functions

Can one rename a built in JavaScript function?可以重命名内置的 JavaScript 函数吗?

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())

You can, but don't你可以,但不要

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. Javascript 足够灵活,允许您像这样更改基本内容,但是如果您以这种方式修改语言的正常部分,您将破坏其他代码并使您自己的代码无法被其他人读取。

That said, you can assign and clear things, even in prototypes like this也就是说,即使在这样的原型中,您也可以分配和清除内容

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.getOwnPropertyDescriptor )中获取该方法的属性描述符,然后使用它来定义一个新属性( Object.defineProperty ),并使用delete前一个:

 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM