THIS 3
| javascriptGonna explore where this
can go wrong by using a series of scenarios.
Scene 3: Borrowing another method that uses this
function Whistle(name) {
this.name = name;
this.bark = function() {
return `The ${this.name} goes WOOOOO WOOOOOOOOO`;
}
};
function Cat(name) {
this.name = name;
this.bark = null;
};
var garfield = new Cat("garfield");
var whistle = new Whistle("whistle");
garfield.bark = whistle.bark();
Ok so garfield wants to bark. Sometimes we must borrow methods from another source. In this example, Garfield would like to bark, but the whistle steals the spotlight. This can be fixed by using apply
. apply
will set this
to its argument:
function Whistle(name) {
this.name = name;
this.bark = function() {
return `The ${this.name} goes WOOOOO WOOOOOOOOO`;
}
};
function Cat(name) {
this.name = name;
this.bark = null;
};
var garfield = new Cat("garfield");
var whistle = new Whistle("whistle");
garfield.bark = whistle.bark.apply(garfield); // The garfield goes WOOOOO WOOOOOOOOO (YES!)
Scene 4: Assign a method that uses this
to a variable
var hunger = {
foods: [
{ place: "gene and jude's", entree: 'depression dog' },
{ place: "pita inn", entree: 'lunch special' },
{ place: "la favorita taqueria", entree: 'carnitas burrito' }
]
};
var lunch = {
foods: [
{ place: "taco bell", entree: 'double stacked taco' },
{ place: "wendy's", entree: 'double stack combo' }
],
order: function() {
var randomNum = Math.floor(Math.random() * 3);
console.log(`Today's order is a ${this.foods[randomNum].entree} from ${this.foods[randomNum].place}.`);
}
};
var todaysOrder = lunch.order;
todaysOrder(); // Today's order is a depression dog from gene and jude's
todaysOrder(); // Today's order is a lunch special from pita inn
todaysOrder(); // Today's order is a carnitas burrito from la favorita taqueria
I thought I was gonna get some fast food, but to my surprise I got something even better. But since the man gots to keep us down, I’m gonna use var todaysOrder = lunch.order.bind(hunger)
to fix this issue and crush some dreams.