14. So what's a method?


#1


bob.setAge = function (newAge){
  bob.age = newAge;
};

Hello, this is a general query. I can't understand how the program knows what to do with the parameter newAge which is not defined anywhere.


#2

a parameter is a placeholder till you call the method, then you supply an argument to satisfy the parameter


#3

In another example, "Introduction to Objects II, 13.How do Classes help us?" it says:

For example, look at our Person class again in the console. We know that any Person will have a name and age, because they are in the constructor. This allows us to create a function like printPersonName, which will take a Person as an argument and print out their name. We know the function will work on any Person, because name is a valid property for that class.

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);

// make a person called me with your name and age
// then use printPersonName to print your name

How does it know that p is a person? Does it search for any type of thing that has a "name" property? I mean, it looks like I could associate anything with that "p". I get it that's it's a placeholder but I don't understand how I point what to associate that placeholder with.


#4

here:

printPersonName(bob);

you call the function/method, so the argument (bob) gets copied into the function/method parameter


#5

Ok, but I wonder how come we don't receive an error message like "p is not defined"?


#6

because p is a placeholder? that is kind of the point of placeholders, no?

functions don't execute unless called, so a placeholder (function parameter) is more then enough till you call the function


#7

Ok thanks. I guess that's clear enough for me now.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.