JavaScript: Constructor Auto-Execution with new Keyword

By  on  

JavaScript is full of small, interesting facets that can trip you up, make you laugh, or make you cry.  This post is about an interesting one.  Those of you that have worked with JavaScript functions, and in a way JavaScript "classes" (as you used with MooTools), you're well acquainted with the new keyword.  With the new keyword you get the ability to pass arguments with the function call, but did you know that if you have no arguments, you don't need the parens at all?

function MyClass() {
	console.log('Initialized!');

	//Set a property, as an example
	this.dirty = true;
}

var instance = new MyClass;

// >> "Initialized!''

So why am I telling you this?  I have no idea.  It's just one of those fun tidbits that you can add to your brain. :)

Recent Features

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

  • By
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

Incredible Demos

  • By
    Add Site Screenshots for External Links Using MooTools Tooltips

    Before you send your user to an unknown external website, why not provide them a screenshot of the site via a tooltip so they may preview the upcoming page? Here's how you can do just that using MooTools. The MooTools JavaScript The first step is to grab...

  • By
    Pure CSS Slide Up and Slide Down

    If I can avoid using JavaScript for element animations, I'm incredibly happy and driven to do so.  They're more efficient, don't require a JavaScript framework to manage steps, and they're more elegant.  One effect that is difficult to nail down with pure CSS is sliding up...

Discussion

  1. Amazing how the obvious is sometimes hidden in plain sight. I was going to save the extra () characters but it looks like there’s a micro performance hit in V8.

    http://jsperf.com/new-with-and-without-parens

    • MaxArt

      Really? That’s ironic, since Google Closure Compiler actually removes the parentheses when they can be omitted.

  2. Kostas Loupasakis

    That was something I always was curious about but never bothered to ask/look up. I assume the same thing also occurs in php?

  3. Asmor

    I’ll file this next to optional semi-colons and optional closing tags in HTML5: things that are interesting to know, but if I ever see while reviewing someone’s code I might get stabby.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!