JavaScript Methods Worksheet
Question 1
How is a method different from a regular function in JavaScript?
A regular function is not tied to anything and stands alone. Whereas a method works with an object it belongs to using 'this' to access the object's property. Essentially, a method is a function within an object.
Example:
Example:
let person = {
name: "Jon Snow",
greet: function(){
return "hello, " + this.name + "!";
}
};
console.log(person.greet()); // it should output: "hello, Jon Snow!"
Question 2
Why would we want to add methods to an object?
Adding methods within an object is useful because it can allow the object to do actions or change it's own data. By doing so, an object is not just storing data, but interacting, updating, and responding to your needs.
Example:
Example:
let car = {
brand: "Honda",
speed: 0,
accelerate: function(){
this.speed += 25;
console.log(this.brand + " is now going " + this.speed + " mph.");
}
};
car.accelerate(); // it should output: "Honda is now going 25 mph"
Question 3
How can we access the property of an object from inside the body of a method of that object?
You can use 'this' which refers to the object. An example of this has been done in problem #1 on how to interact with the property of an object.
Coding Problems
Coding Problems - See the 'script' tag below this h3 tag. You will have to write some JavaScript code in it.
Always test your work! Check the console log to make sure there are no errors.