JSFiddle - React, Tailwind, and code Playground
JavaScript
console.log("normal use");
var carrot = {
name: "carrot",
eat: function () {
console.log(this);
console.log("eating " + this.name);
}
};
function eat() {
console.log(this);
console.log("eating " + this.name);
}
carrot.eat();
eat(); //'this' will be the window object
console.log("apply");
var eggplant = {
name: "eggplant"
};
carrot.eat.apply(carrot);
carrot.eat.apply(eggplant);
eat.apply(carrot);
eat.apply(eggplant);
console.log("bind");
var eatCarrot = eat.bind(carrot);
eatCarrot();
eatCarrot.apply(eggplant);
var eatEggplant = carrot.eat.bind(eggplant);
eatEggplant();
carrot.eat();
console.log("callbacks");
var tammo = {
name: "tammo",
feed: function(callbackFunction) {
return callbackFunction();
},
feedSelf: function(callbackFunction) {
return callbackFunction.apply(this);
},
feedParameter: function(parameter, callbackFunction) {
return callbackFunction.apply(parameter);
}
};
tammo.feed(eat);
tammo.feedSelf(eat);
tammo.feedParameter(carrot, eat);
tammo.feedParameter(eggplant, function() {
console.log(this);
});
//this inside anonymous functions
console.log("this inside anonymous functions");
var cook = {
name: "cook",
cook: function() { //here this is the cook (when we call it normally)
var cook = this; //We have to save "this" to another variable to use it within the anonymous function
tammo.feedParameter(carrot, function() { //here this will be the eggplant
console.log(cook.name + " is cooking a " + this.name + " for " + tammo.name);
});
},
cook2: function() { //here this is the cook (when we call it normally)
var cook = this; //We have to save "this" to another variable to use it within the anonymous function
tammo.feed(function() { //here this will be window (with name "result" in jsfiddle)
console.log(cook.name + " is cooking a " + this.name + " for " + tammo.name);
});
}
}
cook.cook();
cook.cook2();
var restaurant = {
name: "restaurant",
go: function()...