What are pitfalls of extending Object.prototype?

前端 未结 2 1167
生来不讨喜
生来不讨喜 2020-12-11 22:21

I want to extend Object.prototype, to basically support notifications in JSON data and html elements through UI framework.

Object.prototype.setValue = functi         


        
相关标签:
2条回答
  • 2020-12-11 22:35

    I know it fails for(var x in obj), but mostly we can use obj.hasOwnProperty, that should help right?

    That is the only major pitfall, and .hasOwnProperty() helps, but only in your own code. In jQuery, for example, they've taken the deliberate decision not to call .hasOwnProperty in the $.each() method.

    I have used Object.defineProperty(...) in my own code to get around the enumerable property problem with no ill-effects (albeit on Array.prototype)

    0 讨论(0)
  • 2020-12-11 22:43

    You just don't want to mess with prototypes from host or native objects.

    • You cannot know which side effects it has on any third-party script
    • You may confuse third party code
    • You don't know if some day those methods are created natively

    overall, extending Object.prototype effects any other object on the entire site. Again, you just don't want to do it, unless, you are in such a sandboxed environment and every single piece of ecmascript is written on your own and you are 100% sure no third-party script is ever loaded.

    0 讨论(0)
提交回复
热议问题