Hello, I have finally gotten to the OOP section in the curriculum. I understand objects, but can’t get a grasp on prototype. Can someone explain it in a beginner friendly way, or is there a resource online that describes it in a beginner friendly way?
Also look at the reply immediately after it as well which clarifies some of the terms (I was a bit clumsy with the description)
function Programmers(gender, age, firstName, lastName, favourite_lang){
this.gender = gender;
this.age = age;
this.firstName = firstName;
this.favourite_lang = favourite_lang;
this.lastName = lastName
}
Programmers.prototype.getName = function(){
return this.firstName + " " + this.lastName;
}
Programmers.prototype.numLegs = 2;
let p1 = new Programmers("male", 46, "James", "cook", "Go");
let p2 = new Programmers("female", 16, "Peter", "parker", "JavaScript");
let p3 = new Programmers("male", 35, "Eryc", "ramsay", "Python");
console.log(p1.getName);
When i console log it logs function getName()
instead of James cook
. Have i done this correctly?
You mentioned that programmers use the class syntax instead of OOP. Why is that?
No, OOP is just a style of programming – the syntax used doesn’t change that. The way it is taught on FCC shows how it works. But normally in practice you would use the syntax for classes (class MyClass {
), which does exactly the same thing, just code written using class
tends to be easier to read and write.
Can you review the code i posted above, and tell me if its correct?
Programmers.prototype.getName = function(){
getName
is a function, so your log is telling you what it is. How would you use a function?
Oh damn, I forgot the brackets