课程: JavaScript Practice: Scope and Closures
Solution: Scope methods to a function - JavaScript教程
课程: JavaScript Practice: Scope and Closures
Solution: Scope methods to a function
- [Instructor] With our vacation function here, we're creating a destination and length, both of which are going to be scoped to this function. So anytime I pass in a destination and a length, it's going to set that for the vacation. Now if I wanted to add a method to our vacation functions prototype, I would do so using this dot notation, so Vacation.prototype.addTraveler, and then we need to make some adjustments here so that we can define that function. So here we'll say this.travelers.push and we'll push in the name of that traveler. And again, we're setting that here on line eight. We're pushing that into that array. Once I have that set up, we're going to use this createVacation function to create a new vacation object, so I'm just going to call this const trip, or I'll call it desoTrip for desolation, that's where we're going to go, a new vacation with our location and length. Then, I'm going to add a traveler named Alex. So we'll say desoTrip. Remember, because I added that to the prototype addTraveler, we have access to that on our new instance of a vacation. So we'll go ahead and add Alex here. And finally, we're going to return desoTrip.travelers, and what I wanted to find was the first item in that array, so we'll use the index zero. Then, on line 28 here, I'm going to call createVacation. We'll call it with the location Desolation Wilderness, and the length, which is 10. Then I'm going to test my code, so I just need to zoom out a little bit. We'll find that Test my Code button down here. And then we should see that all of our tests have passed. So again, we're scoping this destination and this length to our vacation function. This allows us to create different instances of this vacation. Anytime I want to create a new vacation, I'm also going to have access to this add traveler method.