Created
April 27, 2015 05:28
-
-
Save isramv/8be26e66f5f4797b8f7a to your computer and use it in GitHub Desktop.
JavaScript Functions and OOP with prototype examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Module **/ | |
var MyModule = (function() { | |
var DEFAULT = { | |
param: 'Hello World' | |
} | |
return { | |
name: 'Israel Morales!', | |
say: 'Because YOLO!', | |
speak: function() { | |
console.log('Hello World'); | |
return this; // Like jQuery chaining... | |
}, | |
greet: function() { | |
console.log(this.say); | |
return this; | |
}, | |
hello: function() { | |
console.log(this.say +' '+ this.name); | |
return this; | |
}, | |
helloparams: function() { | |
//var myArguments = arguments[0] || '';//default param if not provided | |
var myArguments = arguments[0] || DEFAULT; | |
console.log(myArguments.param); | |
} | |
} | |
})(); | |
//MyModule.helloparams({ param: 'Aloha!'}); | |
//MyModule.helloparams(); | |
//Passing two objects | |
//MyModule.changeName({ name: 'Israel', lastname: 'Juan'},{name:'Jonathan', lastname: 'Ive'}) | |
/** Scope chain **/ | |
function test() { | |
var name = 'Israel'; | |
var test2 = function() { | |
//var name = 'Jorge'; | |
console.log(name); | |
} | |
test2(); | |
}; | |
//test(); | |
/** Functions inside object **/ | |
var Isra = { | |
name: 'Israel', | |
edad: 31, | |
position: 'Web Developer', | |
sayName: function() { | |
console.log(this.name); | |
} | |
} | |
//console.dir(Isra); | |
/** Object oriented approach **/ | |
var Person = function() { | |
var name; | |
var age; | |
var position; | |
this.name = "Anonimo"; | |
this.age = 29; | |
this.position = "Cashier"; | |
} | |
var yell = function() { | |
return 'Arrrghhh!!!'; | |
} | |
var sayName = function() { | |
return 'My name is: ' + this.name; | |
} | |
var presentYourself = function() { | |
return 'My names is ' + this.name +' and my position is: '+ this.position; | |
} | |
Person.prototype.yell = yell; | |
Person.prototype.sayName = sayName; | |
Person.prototype.aboutMe = presentYourself; | |
var Persona1 = new Person; | |
Persona1.name = "Israel"; | |
Persona1.age = 31; | |
Persona1.position = "Web Developer"; | |
//console.dir(Persona1); | |
var Persona2 = new Person; | |
Persona2.name = 'Priscila Ramos'; | |
//console.dir(Persona2); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment