13/30 how is it possible to use p as a parameter while the object is named Person


#1

How does the function printPersonName know that it should take a Person as an argument, while the parameter in function is not "Person", but just "p"?

function Person(name,age) {
this.name = name;
this.age = age;
}
// a function that prints the name of any given person
var printPersonName = function (p) {
console.log(p.name);
};

var bob = new Person("Bob Smith", 30);
printPersonName(bob);


#2

it works because the argument or object you passed to that function has an attribute called 'name' .
if you call the function with an argument that does not have an attribute called 'name' then you will get undefined

Check out the snippet here


#3

Thanks for the message. I had the same confusion, because I expected the printPersonName method to be part of the Person constructor (which I guess would have been another way of doing it...?) Ok this makes sense - thanks.


#4

if the the function was written inside the the Person class(function) then it will be bound to it . In that case to call it we would have to use the dot(.) notation i.e.

bob.printPersonName();

Check out this snippet here

in this snippet I have added a function called hobby and i call it using the bob object


#5

Thankyou @rydan appreciate the speedy response! Totally understood!