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
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • By
    Fancy Navigation with MooTools JavaScript

    Navigation menus are traditionally boring, right? Most of the time the navigation menu consists of some imagery with a corresponding mouseover image. Where's the originality? I've created a fancy navigation menu that highlights navigation items and creates a chain effect. The XHTML Just some simple...

  • By
    Image Reflection with jQuery and MooTools

    One subtle detail that can make a big difference on any web design is the use of image reflections. Using them too often can become obnoxious but using reflections on large, "masthead" images is a classy enhancement. Unfortunately creating image reflections within your...

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!