开发者

Extending native elements in JavaScript via prototype?

开发者 https://www.devze.com 2023-01-13 12:21 出处:网络
Would you co开发者_运维百科nsider 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.

Would you co开发者_运维百科nsider 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消