A more efficient way to invoke this function?
Hey folks,
I've finally gotten around to learning pure JavaScript a bit better, and I've run into a situation where I think I can optimize my code but I don't know how exactly as I can't find the terms I need to Google this question. I'm currently creating a CSS table header using a function that takes the div as input. This is the code I currently have:
function addTableContent(targetDiv, element, text) {
var cellHeader = document.createElement(element);
var textToAdd = document.createTextNode(text);
targetDiv.appendChild(cellHeader).appendChild(textToAdd);
}
tableCell = createTableSubDiv(calendarTable);
addTableContent(tableCell, "h2", "Event");
I'd like to be able to 'append' the method behind the div as you see with some of the built-ins (e.g. .appendChild). I honestly can't find the term for this, if you do know it then please tell me. To put that into code, I'd like to be able to have it in the following way:
tableCell.addTableContent("h2", "Event");
What exactly would I have to change to get it to work like that?
EDIT: elaboration on question
EDIT2: Thanks for the comments guys, I'll have to sit down and read up on the linked material next!
4 comments · 67% upvoted · other discussions
The way to achieve what you want would be by assigning your function to a property of a prototype of all HTML elements. I'm assuming you've never worked with prototypes in JS before based on your question, so you might find Object prototypes article on MDN interesting.
Your code would look something like this:
So this would certainly work, but what exactly did it do to our app?
We'll be writing the same amount of code, albeit it might look a bit more JavaScript-y
We've potentially broke some code in unrelated places
If someone ever wants to change this code, they need to have an understanding of how prototypes and
thiswork in JS (which is probably OK, since that's their job as JS developers)Given all that, I would advise you to not do what you set out to do and stick to your current implementation, using a regular function — your code will be just simpler that way.