Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do I know which way to create an object in JavaScript when you just taught me four different ways to do it?

The OO JavaScript course demonstrated four ways for creating a JavaScript object. My question is, why would I use one over another? Here are the four methods we were taught. Which one should I use and why?

(Method #1) function Apple (type) { this.type = type; this.color = "red"; }

Apple.prototype.getInfo = function() { return this.color + ' ' + this.type + ' apple'; };


(Method #2) var apple = { type: "macintosh", color: "red", getInfo: function () { return this.color + ' ' + this.type + ' apple'; } }


(Method #3) function Apple (type) { this.type = type; this.color = "red"; this.getInfo = function() { return this.color + ' ' + this.type + ' apple'; }; }


(Method #4) function Apple (type) { this.type = type; this.color = "red"; this.getInfo = getAppleInfo; }