Let's say you want to add a method to all the elements in your HTML document. Normally, to do this, you will use Element.prototype
as below:
Element.prototype.foo = function() {
return "foo";
};
Let's say now you want to include a library called bar.js in your document. But unbeknownst to to you, there is a piece of code in bar.js that overwrites the foo()
method of Element.prototype
as below:
Element.prototype.foo = function() {
return "bar";
}
Now, when you call the foo()
method of an element, it returns "bar" instead of "foo" as you'd expect.
How to prevent this?
One way is to call Object.seal()
or Object.freeze()
on Element.prototype
. But it's a really bad practice. (What if some other code wants to modify another property or method of Element.prototype
?)
However, there's another way that allows you to add an immutable method to an existing class without affecting any of its other behaviours: using Object.defineProperty
.
Object.defineProperty(Element.prototype, "foo", {
value: function() {
return "foo";
}
});
Any properties created using Object.defineProperty
are immutable by default. So this will prevent other code from overwriting or removing foo()
while leaving the other properties and methods of Object.prototype
available for modification.