7

In javascript, it's possible to "override" properties or methods of Object.prototype. For example:

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

It can break an entire application if not used carefully. Are there any tools, techniques or approaches to avoid this (for example, some kind of 'strict mode' that doesn't allow the developer to override properties of Object)?

5
  • 5
    Just don't do it and don't take in any libraries that do? Commented Jul 22, 2017 at 17:17
  • 3
    Object.freeze(Object.prototype) will help, but again.. don't know how much pollution it will create Commented Jul 22, 2017 at 17:21
  • 3
    A good read for anyone that lands on this question: esdiscuss.org/topic/object-freeze-object-prototype-vs-reality Commented Jul 22, 2017 at 17:28
  • @RayToal: Fantastic link, I've added it to the CW answer below. Commented Jul 22, 2017 at 17:30
  • See here on how to do this carefully and not break applications Commented Jul 22, 2017 at 18:01

1 Answer 1

7

Object.freeze(YourConstructor.prototype) can help protect your constructor's associated prototype object from being mucked with. From 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.

It works on the object itself, rather than making a copy that's frozen. It returns the same reference you pass it.

It's best to leave built-in prototypes alone, so using it on Object.prototype and such may not be a great idea. :-) Certainly you'd need to do a lot of testing if you did... See this thread on the es-discuss mailing list for relevant, useful info.

Sign up to request clarification or add additional context in comments.

4 Comments

hmm, but a simple thing I want to add (or may be ask), what is the point of doing this if some attack de-refer the Object itself?
@KoushikChatterjee These techniques only can help to prevent third parties from accidentally breaking your application. They never can secure it against an attacker. If you have anyone run unrestricted code on your page, you've already lost.
+1 because you can lock your doors but you can't put bear traps in your own house, that's not how security works.
@Bergi yeah that's the conceptual stuff about XSS , but the point of my comment was, is there any way further to prevent that (though we know, preventing XSS is not at all a good idea because its already too late)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.