有什么理由不改变js原型? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

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

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

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

是否有功能原因不这样做?

javascript prototype primitive
1个回答
0
投票

是的,有理由不这样做,一个立即跳出来的是你将不可避免地与另一个库相撞,该库也认为更容易调整内置原型。

考虑以下:

// 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函数以及何时使用。

您还可以利用tree shaking的优势。

考虑无污染的例子:

// 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));
© www.soinside.com 2019 - 2024. All rights reserved.