//Greeting Library
// 1. create self initialing function, which takes two params
;(function (global, $) {
// 3. set Greetr to a constructor function that returns an new Object
var Greetr = function (firstName, lastName, language) {
return new Greetr.init(firstName, lastName, language);
}
//Hidden within the scope of the IIFE
var supportedLangs = ['en', 'es'];
//informal greetings
var greetings = {
en: "hello",
es: 'Hola'
};
//formal greetings
var formalGreetings = {
en: 'Greetings',
es: 'Saludos'
};
// login messages
var logMessages = {
en: 'logged in',
es: 'inicio sesion'
}
// 6. Create our prototype containing required methods
Greetr.prototype = {
fullName: function () {
return this.firstName + ' ' + this.lastName;
},
validate: function () {
if (supportedLangs.indexOf(this.language) === -1) {
throw "invalid laguage";
}
},
greeting: function () {
return greetings[this.language] + ' ' + this.firstName;
},
formalGreeting: function () {
return formalGreetings[this.language] + ' ' + this.fullName();
},
greet: function (formal) {
var msg
if (formal) {
msg = this.formalGreeting();
} else {
msg = this.greeting();
}
if (console) {
console.log(msg);
}
return this;
},
setLang: function(lang) {
this.language = lang;
this.validate();
return this;
},
log: function(){
if (console){
console.log(logMessages[this.language] + ': ' + this.fullName());
}
return this;
},
HTMLGreeting: function(selector, formal){
if (!$) {
throw 'jQuery not loaded';
}
if (!selector) {
throw 'invalid selector';
}
var msg;
if (formal) {
msg = this.formalGreeting();
} else {
msg = this.greeting();
}
$(selector).html(msg);
return this;
}
};
// 4. create our function to set default values to be used by our prototype methods
Greetr.init = function (firstName, lastName, language){
var self = this;
self.firstName = firstName || '';
self.lastName = lastName || '';
self.language = language || "en";
}
// 5. Set our greetr.init functions protptype to our Greetr Prototype to access is methods
Greetr.init.prototype = Greetr.prototype;
// 7. Create global variable Greetr equal to Greetr & global.G$ to call externally
global.Greetr = global.G$ = Greetr;
}(window, jQuery)); // 2. pass the function the window as the global object and jQuery