每个JS意见领袖都说扩展原生对象是一种不好的做法.但为什么?我们是否获得了性能?他们是否害怕有人以"错误的方式"做到这一点,并添加了可枚举的类型Object,几乎破坏了任何对象上的所有循环?
以TJ Holowaychuk的should.js为例.他增加了一个简单的getter来Object,一切工作正常(来源).
Object.defineProperty(Object.prototype, 'should', {
set: function(){},
get: function(){
return new Assertion(Object(this).valueOf());
},
configurable: true
});
Run Code Online (Sandbox Code Playgroud)
这真的很有道理.例如,可以扩展Array.
Array.defineProperty(Array.prototype, "remove", {
set: function(){},
get: function(){
return removeArrayElement.bind(this);
}
});
var arr = [0, 1, 2, 3, 4];
arr.remove(3);
Run Code Online (Sandbox Code Playgroud)
是否有任何反对扩展本机类型的论据?