什么是扩展Object.prototype的陷阱? [英] What are pitfalls of extending Object.prototype?

查看:175
本文介绍了什么是扩展Object.prototype的陷阱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展Object.prototype,基本上通过UI框架支持JSON数据和html元素中的通知。

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);
};

但是,根据这个问题,扩展Object.prototype JavaScript 和其他一些人,人们说我们应该避免扩展Object.prototype,而不是任何其他类型。

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");

必须写成,

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

我想知道如果我使用这些方法会出现什么问题?它会导致jQuery出乎意料吗?我曾经看过,jQuery的ajax请求也会调用原型方法(因为它们引用了事件处理函数)。

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).

这有什么其他副作用?我知道它失败了(var x in obj),但大多数情况下我们可以使用obj.hasOwnProperty,这应该对吗?

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?

推荐答案

你只是不想搞乱来自主机或本机对象的原型。

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


  • 你无法知道它对任何第三方有什么副作用-party script

  • 您可能会混淆第三方代码

  • 您不知道某些方法是否有一天本地创建

总体而言,扩展 Object.prototype 影响整个任何其他对象现场。再说一次,你只是不想这样做,除非你处于这样一个沙盒环境中,每一片ecmascript都是你自己编写的,你百分之百确定没有加载第三方脚本。

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.

这篇关于什么是扩展Object.prototype的陷阱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆