簡體   English   中英

重命名內置 javascript 函數

[英]Renaming built in javascript functions

可以重命名內置的 JavaScript 函數嗎?

我正在嘗試將“反向”功能重命名為另一個名稱,但仍然具有相同的功能

您可以通過在函數原型中創建別名來更改名稱

 Array.prototype.newreversename = Array.prototype.reverse; var arr=["abc","sssd"]; console.log(arr.newreversename())

您還可以為新函數創建一個包裝函數

 Array.prototype.newreversefunction = function() { return this.reverse(); }; var arr=["a","c"]; console.log(arr.newreversefunction())

你可以,但不要

這稱為猴子修補。 Javascript 足夠靈活,允許您像這樣更改基本內容,但是如果您以這種方式修改語言的正常部分,您將破壞其他代碼並使您自己的代碼無法被其他人讀取。

也就是說,即使在這樣的原型中,您也可以分配和清除內容

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"

可以,但我強烈建議不要這樣做。

正確的做法是從原型( 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

你可以這樣做:

Array.prototype.myReverse = Array.prototype.reverse;
delete Array.prototype.reverse;

但是您應該避免這種情況,因為許多庫依賴於反向功能。 相反,如果您想使用其他名稱調用它,只需執行第一行:

Array.prototype.myReverse = Array.prototype.reverse;

您可以通過創建別名來更改名稱

 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