如何避免 javascript 中的原型污染?

How to avoid prototype pollution in javascript?

在 javascript 中,可以 "override" Object.prototype 的属性或方法。例如:

Object.prototype.toString = function(){
  return "some string";
};

如果不小心使用,它可能会破坏整个应用程序。是否有任何工具、技术或方法可以避免这种情况(例如,某种 'strict mode' 不允许开发人员覆盖对象的属性)?

Object.freeze(YourConstructor.prototype) 可以帮助保护 你的 构造函数的关联原型对象不被破坏。来自 MDN:

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed.

它对对象本身起作用,而不是制作冻结的副本。它 returns 与您传递给它的引用相同。

最好不要使用内置原型,因此在 Object.prototype 上使用它可能不是一个好主意。 :-) 当然,如果您这样做的话,您需要进行 大量 测试...请参阅 es-discuss 邮件列表中的 this thread 以获取相关的有用信息。