通过原型扩展 JavaScript 中的原生元素?
您会考虑通过危险的原型扩展原生元素吗?我看到一些框架(例如 Prototype)这样做,所以我开始怀疑我是否也敢这样做。
我担心实现像 addClassName 这样的东西,并使其在未来发生冲突,除了重写软件并要求模块作者做同样的事情之外,我无法通过任何其他方式解决。
Would you consider extending the native elements via the prototype dangerous? I see some frameworks such as Prototype doing this so I have started to wonder if I dare to do that too.
I am worried about implementing things like addClassName and make it collide in the future in a way that I can't resolve any other way than rewriting the software and asking module authors to do the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不会,因为恕我直言,它肯定会很快或以后发生冲突,并产生一个很难被发现的潜在错误。
无论如何,我确实扩展了一些基本简单本机Javascript对象,例如 String.trim,无论如何,我总是小心地使用简单的 if 测试来测试它是否已经存在:
您可以使用 addClassName 执行相同的操作。
不同之处在于,使用像 String.trim 这样的简单函数来实现这一点是很困难的,这可能会导致将来出现问题,因为即使浏览器引擎有 String.trim (实际上 FF 有它),这样的函数也将完全执行此操作我的 String.trim 所做的事情,因此您永远不会看到 Web 应用程序工作流程中的差异。
更复杂的函数(例如覆盖 querySelectorAll)可能会导致浏览器实现它的方式与您的实现方式之间存在差异。例如:返回元素的顺序可能不同,浏览器函数返回一个集合,而您的返回一个数组,以及其他问题。因此,当您在实现了 querySelectorAll 的浏览器上运行 Web 应用程序时,可能会导致您的 Web 应用程序不再按预期工作,并尝试找出错误!
也许 querySelectorAll 不是最好的例子,但我希望我解释了这个概念。
I wouldn't because IMHO it might definitely make collisions soon or later and create a potential bug very difficult to be spot out.
I anyway do extend some basic simple native Javascript objects like String.trim, I'm anyway careful to always test to see if it already exists by using a simple if test:
You could do the same with addClassName.
The difference is that doing it with simple function like String.trim, it's difficult that might lead to problems in future, because even if a browser engine has got String.trim (actually FF has it) well such a function is going exactly to do what my String.trim does, so you won't see differences in your web application workflow ever.
A more complex function like overriding querySelectorAll might lead to differences between how the browser implements it and your implementation. For example: the order of the returned elements might be different, the browser function returns a collection while your one an array, and other issues. So when you run your webapp on browser that does implement the querySelectorAll it might lead to having your webapp not working anymore as expected, and there try finding out the bug!!!
Maybe querySelectorAll is not the best example, but I hope I explained the concept.