问题描述
你会考虑通过原型将本机元素扩展为危险的吗?我看到一些框架,如Prototype这样做,所以我开始怀疑我是否也敢做。我担心实现像addClassName这样的事情,并在将来发生冲突,我无法解决任何其他方式,比重写软件和询问模块作者要做同样的事情。
我不会因为IMHO很可能会在短时间内发生冲突,并创建一个潜在的错误很难被发现。
我无论如何都会扩展一些基本简单的本机Javascript对象,如String.trim,我反正小心总是通过使用简单的测试来测试它是否已经存在:
if(!String.prototype.trim)
String.prototype.trim = function(){return this.replace(/ ^ \s\s * /,'').replace(/ \s\s * $ /,''); }
你可以使用addClassName做同样的事情。
不同的是,使用像String.trim这样简单的函数来做,今后很难导致问题,因为即使浏览器引擎已经有String.trim(实际上是FF),这样一个函数就是要完全做我的String.trim做的,所以你不会看到你的Web应用程序工作流程的差异。
更复杂的功能,如覆盖querySelectorAll可能会导致浏览器实现它与实现之间的差异。例如:返回的元素的顺序可能不同,浏览器函数返回一个集合,而你的一个数组等问题。所以当你在浏览器上运行webapp的时候,它实现了querySelectorAll,它可能会导致你的webapp不再像预期的那样工作,而且尝试找出错误!!!
也许querySelectorAll不是最好的例子,但我希望我解释了这个概念。
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.
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:
if(!String.prototype.trim)
String.prototype.trim = function() { return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }
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.
这篇关于通过原型在JavaScript中扩展本机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!