JavaScript - function 101 - build up to it

by secretgspot

JavaScript

//OK, but its in the global namespace
//function Apple(type) {
var Apple = function(type) {
    this.type = type;
    this.color = "red";
    //this.getInfo = getAppleInfo;
    /* this is fine, bu why not prototype it */
    /*
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
    */
}

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

// anti-pattern! 
// as its in the global namespace.
/*
function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}
*/

// better, but if its just used one place, 
// why not embed it.
/*
var getAppleInfo = function() {
    return this.color + ' ' + this.type + ' apple';
};
*/


var apple = new Apple('macintosh');
apple.color = "reddish";
console.log(apple.getInfo());