Extending native elements in JavaScript via prototype?

前端 未结 1 1811
别跟我提以往
别跟我提以往 2021-01-15 05:39

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

相关标签:
1条回答
  • 2021-01-15 06:03

    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 讨论(0)
提交回复
热议问题