spencer.sm
spencer.sm

Reputation: 20614

Constructor function to create DOM elements

I'm trying to use a constructor function to help create DOM elements but I'm wondering if there was a preferred way to do so. I know I could use a framework to do with this but I'd like to implement it using vanilla JavaScript.

Both ways shown below seem to work but I haven't used the new operator with functions very much. Is there any difference between the two ways? Would I be better just to use a plain old function in this situation and not use new?

// First way
function Title(text){
  this.element = document.createElement('h2');
  this.element.innerText = text;
  return this.element;
}

// Second way
function Title(text){
  var element = document.createElement('h2');
  element.innerText = text;
  return element;
}

var title = new Title("Hello");
document.body.appendChild(title);

Upvotes: 0

Views: 1099

Answers (1)

frogatto
frogatto

Reputation: 29285

Your first way does't seem to be correct. Though it works, you seems you haven't understood how new works in JavaScript. When you use new with a function, the following steps are taken:

  • An empty object is created, something like {}.
  • All this references inside the function refer to that empty object.
  • this is used to populate that empty object as needed.
  • implicitly this is returned. (If you explicitly return, this will be ignored.)

Note that in a constructor function, if you explicitly return something other than this, the returned value is not instanceof that constructor function. Only this is instanceof the constructor function.

Therefore, the first way has nothing to do with logic of new. It's logically the same as the second one.

Upvotes: 3

Related Questions