What are pitfalls of extending Object.prototype?

2020-02-07 03:53发布

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

Object.prototype.setValue = function(key,value){
   // this simply sets value as this[key] = value
   // and raises an event
   Binder.setValue(this,key,value);
};
Object.prototype.getValue = function(key){
   return Binder.getValue(this,key);
};

However, based on this question, Extending Object.prototype JavaScript and few others, people say that we should avoid extending Object.prototype, instead any other type is fine.

If I do not do this, then my code becomes bigger, for example

window.myModel.setValue("currentStatus","empty");

will have to be written like,

Binder.setValue(window.myModel,"currentStatus","empty");

I want to know what will go wrong if I use these methods? will it cause jQuery to behave unexpectedly? I have seen once, that jQuery's ajax request invokes prototype methods as well (as they references to functions for event handling).

What are other side effects of this? I know it fails for(var x in obj), but mostly we can use obj.hasOwnProperty, that should help right?

2条回答
▲ chillily
2楼-- · 2020-02-07 04:02

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.

查看更多
神经病院院长
3楼-- · 2020-02-07 04:20

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)

查看更多
登录 后发表回答