为什么不更改js原型



我经常使用某些算法,因此我正在考虑将它们添加到我的应用程序中的原型中。例如,数组中的最后一个值。与每次我想要数组中的最后一个值时写入arr[arr.length -1]相比,array.last()非常方便。

当我的应用程序第一次加载时,我会这样做。

Object.defineProperty(Array.prototype, 'last', {
value: function(){return this[this.length -1]} })

是否有功能上的理由不这样做?

是的,不这样做是有原因的,一个立即跳出来的原因是,您将不可避免地与另一个库发生冲突,而认为调整内置原型更容易。

考虑以下内容:

// my-cool-library.js
// Returns the last value in an array
Array.prototype.last = function() {
return this[this.length - 1];
}
// some-other-cool-library.js
// Returns the last possible index of the array
Array.prototype.last = function() {
return this.length - 1;
}
// some-consumer.js
import "my-cool-library.js";
import "some-other-cool-library.js";
const a = ["a", "b", "c"];
// You would probably expect it to print "c", but it prints 2
console.log(a.last());

你可能认为这不太可能,但如果你使用真正大的框架呢?假设您同时使用Angular和lodash。像Angular这样的大型框架想要通过在某些Object原型中添加一些辅助函数来简化生活,这并不完全不可能。然而,lodash是一个范围非常广泛的库,它还为您可能想要对集合执行的几乎每个操作添加了辅助函数。

很可能这两个库都希望使用相同、简洁的辅助函数名,但可能没有相同的函数签名。突然之间,您应该如何调用和使用Array.prototype.last变得不明显了。

相反,当您利用依赖项注入并编写函数来获取执行计算所需的所有参数并且不污染原型时,会更受欢迎。这样,您就可以准确地决定使用哪个last函数以及何时使用。

你还可以利用摇树的好处。

以无污染为例:

// my-cool-library.js
// Returns the last value in an array
export function last(arr) {
return arr[arr.length - 1];
}
// some-other-cool-library.js
// Returns the last possible index of the array
export function last(arr) {
return arr.length - 1;
}
// some-consumer.js
import {last as myLast} from "my-cool-library.js";
import {last} from "some-other-cool-library.js";
const a = ["a", "b", "c"];
// You know that you're going to use myLast 
// and how it is going to act
console.log(myLast(a));

最新更新