Home > Software engineering >  Adding properties to DOM objects and functions, and to the window object?
Adding properties to DOM objects and functions, and to the window object?

Time:09-09

I've read a number of questions that state it is unwise to add properties to DOM element objects; and they seem to make a great deal of sense. The best suggestion I came across to accomplish the same end was to use a Weak Map with the DOM node reference as the key.

That led me to wonder about adding properties to function objects. Is that "safe" to do or should another object or map be used for this also. I'm referring to functions on the window object. Can the property names I add clash with names in the function object in the future?

That brings up a related matter I've been trying to understand which is that some claim that the window object is so cluttered up that it ought not to be added to and scripts should be modules now. Modules appears to be more isolated than my limited experience with simple namespaces. Is there anything to be gained through using scripts of type module over just declaring another object and making your functions methods of that object? That object would still be added to the window object.

Thank you.

CodePudding user response:

That led me to wonder about adding properties to function objects. Is that "safe" to do or should another object or map be used for this also. I'm referring to functions on the window object. Can the property names I add clash with names in the function object in the future?

It's not safe in that, if you do it, others could do it too. For example:

// Your code
RegExp.description = 'some description for the constructor!';
setTimeout(() => {
  console.log(RegExp.description);
});

// Someone else's code
RegExp.description = "someone else's description";

The only consolation is that it's pretty unlikely for such a thing to happen.

Similarly, it's pretty unlikely for some random English word that one library creates for itself on the window collides with another word that another library creates for itself on the window - but it's not impossible. For that reason

That object would still be added to the window object.

can be seen as slightly less than optimal on huge pages, where collisions are a real possibility.

Is there anything to be gained through using scripts of type module over just declaring another object and making your functions methods of that object?

Yes, see above. If all of your code is in module scripts, there should be no need to put any object onto the window, in most cases. In addition to the above, module scripts often make projects easier to manage because they make all dependencies explicit through the use of import statements. They're also very easily integrated into a build process like Webpack - and build processes allow for all sorts of neat things that aren't easily done otherwise.

  • Related