Created
October 12, 2016 22:21
-
-
Save Sysetup/49022b2deb61ca8e5e0ebd614d3f6872 to your computer and use it in GitHub Desktop.
Object prototype (Object constructor function) basic example.
This file contains hidden or 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
var txt = ""; | |
var x; | |
function Person(first, last, age, sex) { //Object prototype (Object constructor function) | |
this.firstName = first; | |
this.lastName = last; | |
this.age = age; | |
this.sex = sex; | |
this.changeFirstName = function (name) { | |
this.firstName = name; | |
}; | |
} | |
var you = new Person("Nydia", "Garz", 50, "F"); | |
var me = new Person("Carlos", "Rami", 25, "M"); | |
you.changeFirstName('Nxdxa'); | |
you.nationality = "English"; //Adding property. | |
me.fullName = function(){ return this.firstName + " " + this.lastName } //Adding function. | |
delete you.age; //Deleting property. Or delete you["age"]; | |
/* | |
It isn't posible add a new property to a prototype the same way as add a new property to an | |
existing object, because the prototype is not an existing object. Then, this is the way: | |
The JavaScript prototype property allows you to add new properties or methods to an existing prototype: | |
*/ | |
Person.prototype.race = "Latin"; | |
/* | |
Person.prototype.race; | |
you.race = "Latin"; | |
me.race = "White"; | |
*/ | |
console.log("Your first name is " + you.firstName + ", your race is " + you.race + ". I'm " + me.age + " years old and my fullname is " + me.fullName() + ", my race is " + me.race + "."); | |
for (x in me) { //Exploring object's properties. | |
txt += me[x] + "\n"; | |
} | |
console.log('Txt: \n' + txt); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment