为什么扩展本机对象是一种不好的做法? [英] Why is extending native objects a bad practice?

查看:122
本文介绍了为什么扩展本机对象是一种不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个JS意见领袖都表示扩展原生对象是一种不好的做法。但为什么?我们是否获得了性能?他们是否害怕有人以错误的方式做到这一点,并将可枚举的类型添加到 Object ,几乎会破坏任何对象上的所有循环?

Every JS opinion leader says that extending the native objects is a bad practice. But why? Do we get a perfomance hit? Do they fear that somebody does it "the wrong way", and adds enumerable types to Object, practically destroying all loops on any object?

参加 TJ Holowaychuk should.js 例如。他添加一个简单的getter 对象,一切正常(来源)。

Take TJ Holowaychuk's should.js for example. He adds a simple getter to Object and everything works fine (source).

Object.defineProperty(Object.prototype, 'should', {
  set: function(){},
  get: function(){
    return new Assertion(Object(this).valueOf());
  },
  configurable: true
});

这真的很有意义。例如,可以扩展 Array

This really makes sense. For instance one could extend Array.

Array.defineProperty(Array.prototype, "remove", {
  set: function(){},
  get: function(){
    return removeArrayElement.bind(this);
  }
});
var arr = [0, 1, 2, 3, 4];
arr.remove(3);

是否有任何反对扩展本机类型的参数?

Are there any arguments against extending native types?

推荐答案

扩展对象时,可以更改其行为。

When you extend an object, you change its behaviour.

更改仅使用的对象的行为你自己的代码很好。但是当你改变其他代码也使用的东西的行为时,你可能会破坏其他代码。

Changing the behaviour of an object that will only be used by your own code is fine. But when you change the behaviour of something that is also used by other code there is a risk you will break that other code.

当它向对象添加方法时javascript中的数组类,由于javascript的工作方式,破坏某些东西的风险非常高。多年的经验告诉我,这种东西会导致javascript中出现各种可怕的错误。

When it comes adding methods to the object and array classes in javascript, the risk of breaking something is very high, due to how javascript works. Long years of experience have taught me that this kind of stuff causes all kinds of terrible bugs in javascript.

如果您需要自定义行为,那么定义自己的行为要好得多class(可能是子类)而不是更改本机的类。这样你就不会破坏任何东西。

If you need custom behaviour, it is far better to define your own class (perhaps a subclass) instead of changing a native one. That way you will not break anything at all.

能够在没有子类的情况下改变类的工作方式是任何优秀编程语言的一个重要特征,但它是一个必须很少使用并谨慎使用。

The ability to change how a class works without subclassing it is an important feature of any good programming language, but it is one that must be used rarely and with caution.

这篇关于为什么扩展本机对象是一种不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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