On Github tbashor / understanding-this
var animal = function(){}; animal.prototype.speak = function(){ console.log( this.says ); // uses object's property }; var dog = new animal(); dog.says = 'woof'; var cat = new animal(); cat.says = 'meow'; dog.speak(); // woof cat.speak(); // meow
// callbacks can be tricky function speak() { console.log( this.says ); } function doTrick( trick ) { trick(); } var dog = { says: 'woof', speak: speak }; var says = "oops, global"; // `says` also property on global object doTrick( dog.speak ); // "oops, global"
function speak() { console.log( this.says ); } function doTrick( trick ) { trick(); } var dog = { says: 'woof', speak: speak }; var says = "oops, global"; doTrick( dog.speak );
function speak() { console.log( this.says ); } function doTrick( trick ) { trick(); // <-- CALL-SITE!! } var dog = { says: 'woof', speak: speak }; var says = "oops, global"; doTrick( dog.speak ); // dog.speak is just a reference
function animal( says ) { this.says = says; } var dog = new animal('woof'); console.log( dog.says ); // woof
function louder() { return this.says.toUpperCase(); } function speak() { var greeting = louder.call( this ) + '! I can talk.'; console.log( greeting ); } var dog = { says: "woof" }; var cat = { says: "meow" }; louder.call( dog ); // WOOF louder.call( cat ); // MEOW speak.call( dog ); // WOOF! I can talk. speak.call( cat ); // MEOW! I can talk.
function louder( context ) { return context.say; } function speak( context ) { var greeting = louder.call( context ) + '! I can talk.'; console.log( greeting ); } var dog = { say: "woof" }; // Just use the functions louder( dog ); // WOOF speak( dog ); // WOOF! I can talk.
function speak() { 'use strict'; console.log( this.say ); } var say = 'baa'; speak(); // TypeError: `this` is `undefined`
function speak() { console.log( this.say ); } var say = 'baa'; speak(); // baa
function Dog(){ this.say = 'woof'; setInterval(() => { this.say++; // |this| properly refers to the person object }, 1000); } var barkingDog = new Dog();
github.com/tbashor/understanding-this TheStartersAcademy.com / 858.876.CODE