Jump to content

interesting function constructor behavior


skaterdav85

Recommended Posts

I've been reading JavaScript Patterns and one of the topics discussed is forcing function constructors to work properly even if the new operator was not used. Thus if you invoke a constructor as a regular function, it will still return a new instance of the object.

function Waffle () {	if(!(this instanceof Waffle)) {		return new Waffle();	}			this.taste = "Good";}var w1 = new Waffle(),	  w2 = Waffle();	document.write(w1.taste); //outputs "Good"document.write('<br/>');document.write(w2.taste); //outputs "Good"

In this example, both w1 and w2 contain the property taste with a value of Good. What is interesting is that when Waffle is invoked as a regular function and the result is assigned to the variable w2, wouldn't the line this.taste = "Good" not get executed because of the return statement right above it? It still does get executed however and both w1 and w2 contain a taste property. Anyone know why?

Link to comment
Share on other sites

Hmm...This is only speculation:The if statement is checking to see if this is an instance of Waffle, and if it isn't create a new instance. When you call the constructor as a regular method, this doesn't appear to be an instance of Waffle, so it creates one just like you do when you created the w1 object (using the 'new' keyword, that is). So it calls the constructor again, this time using the 'new' keyword, which I assume means that this is then an instance of Waffle. And because this is now an instance of Waffle, it skips that if block and executes the line that defines the taste property.Boy, I don't know if I understand what I just wrote... :) :)

Link to comment
Share on other sites

@big_dave, you asked a while back what Crockford means when he says JavaScript has a lot of "expressive power." Having little operators like instanceof and typeof is just one of the ways a language gets that. I've been using typeof a lot lately. There's a lot of stuff you just couldn't do without that stuff, or the workarounds would be insane, ya know?

Link to comment
Share on other sites

im surprised i didn't know about the typeof operator when I first learned JS in school. I remember seeing weird workaround examples to check if data was a number or not. typeof seems easy and to the point. its slowly coming to together!

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...