I'm a new comer to JS & working my way around it. I was trying to test my JS skills, so I decided to write down a simple code that displays employees information in the console and indeed I wrote it, but in a way different from what I've learned from 2 tutorials, the first explaining "How to create objects & methods" and the second explaining "The prototype objects". Although, the results are pretty identical. So if anyone could help me to understand the difference, I'd be very grateful.
Important !!
- If you want to test the code, please open your console!
- I couldn't paste the link to the third code because I still don't have enought reputation points to post more than 2 link. Sorry.
This is the project using my method (JSFIDDLE: http://jsfiddle.net/9NUGC/)
var peter = {name:"Peter", age:"23", sex:"Male", country:"Russia", position:"Manager"};
var mark = {name:"Mark", age:"21", sex:"Male", country:"US", position:"Designer"};
var jessica = {name:"Jessica", age:"19", sex:"Female", country:"UK", position:"Programmer"};
function showDetailsInLog(x){
console.log("Employee Name: " + x.name);
console.log("Employee Age: " + x.age);
console.log("Employee Sex: " + x.sex);
console.log("Employee Country: " + x.country);
console.log("Employee Position: " + x.position);
console.log("-----------------------");
}
showDetailsInLog(peter);
showDetailsInLog(mark);
showDetailsInLog(jessica);
This is the project using the method in "Creating objects & methods" tutorial (JSFIDDLE: http://jsfiddle.net/s5d64/)
var peter = {name:"Peter", age:"23", sex:"Male", country:"Russia", position:"Manager"};
var mark = {name:"Mark", age:"21", sex:"Male", country:"US", position:"Designer"};
var jessica = {name:"Jessica", age:"19", sex:"Female", country:"UK", position:"Programmer"};
function showDetailsInLog(){
console.log("Employee Name: " + this.name);
console.log("Employee Age: " + this.age);
console.log("Employee Sex: " + this.sex);
console.log("Employee Country: " + this.country);
console.log("Employee Position: " + this.position);
console.log("-----------------------");
}
peter.logInfo = showDetailsInLog;
mark.logInfo = showDetailsInLog;
jessica.logInfo = showDetailsInLog;
peter.logInfo();
mark.logInfo();
jessica.logInfo();
This is the project using the method in "Prototype objects" tutorial
function Employee(n, a, s, c, p) {
this.name = n;
this.age = a;
this.sex = s;
this.country = c;
this.position = p;
}
Employee.prototype.logInfo = function() {
console.log("Employee Name: " + this.name);
console.log("Employee Age: " + this.age);
console.log("Employee Sex: " + this.sex);
console.log("Employee Country: " + this.country);
console.log("Employee Position: " + this.position);
console.log("-----------------------");
}
var peter = new Employee("Peter", "23", "Male", "Russia", "Manager");
var mark = new Employee("Mark", "21", "Male", "US", "Designer");
var jessica = new Employee("Jessica", "19", "Female", "UK", "Programmer");
peter.logInfo();
mark.logInfo();
jessica.logInfo();