javascript原型
As programmers, one of the skills we must first learn is how to search for a solution.
作为程序员,我们首先要学习的技能之一就是如何寻找解决方案。
Google is your friend. And most of the times a StackOverflow answer back from 2009 is the perfect solution to your 2019+ problem.
Google是您的朋友。 在大多数情况下,2009年以来的StackOverflow答复都是解决2019年以上问题的完美解决方案。
On that specific site, or on personal blogs, I sometimes see code that modifies built-in Objects prototypes.
在该特定站点或个人博客上,我有时会看到修改内置Objects原型的代码。
Like in this example, where the Array object prototype is enhanced by adding an insert
method:
像在此示例中一样,通过添加insert
方法来增强Array对象原型:
Array.prototype.insert = function(index, item) {
this.splice(index, 0, item)
}
In this way, you can have any array and call insert() on it:
这样,您可以拥有任何数组并在其上调用insert():
['red', 'blue'].insert(0, 'yellow')
It’s handy. Instead of having to define such function and worry about the scope of it, you attach it to the Array object, so that every array has it available.
很方便 不必定义此类函数并担心其范围,您可以将其附加到Array对象,以便每个数组都可用。
But just because you can, it does not mean you should.
但是,仅仅因为您可以 ,并不意味着您应该这样做。
What’s wrong with this approach?
这种方法有什么问题?
可能的冲突 (Possible conflicts)
Suppose a library you use implements such thing. And another library you import does the same. Perhaps the methods work slightly differently, and things seem to work fine until they don’t.
假设您使用的库实现了这种事情。 您导入的另一个库也是如此。 也许这些方法的工作方式略有不同,并且直到它们不起作用为止,一切似乎都可以正常工作。
You have a big problem here, because you can’t modify those libraries but you still want to use them.
您在这里遇到了一个大问题,因为您无法修改这些库,但仍想使用它们。
将来验证您的代码 (Future-proofing your code)
Suppose the next version of JavaScript implements the Array.insert
method. With a different signature. Now what happens? You need to go back and rewrite all the code you wrote. Perhaps for a client you don’t work for anymore.
假设下一个JavaScript版本实现Array.insert
方法。 具有不同的签名。 现在会发生什么? 您需要返回并重写所有编写的代码。 也许对于客户而言,您不再工作了。
Or maybe you did this in a library that’s used by other people in their own projects. That would be even worse.
也许您是在其他人在自己的项目中使用的库中完成此操作的。 那会更糟。
This approach only creates technical debt and pretty much invites problems.
这种方法只会产生技术债务,并且几乎会引发问题。
您应该怎么做呢? (What should you do instead?)
Create a function in a library file and import it when you want to use it. Don’t modify objects you have no control over.
在库文件中创建一个函数,并在要使用它时将其导入。 不要修改您无法控制的对象。
翻译自: https://flaviocopes.com/javascript-why-not-modify-object-prototype/
javascript原型