├── index.html └── this.js /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Broken 9 | Working 10 | Ajax Broken 11 | Ajax Working 12 | Ajax Also Working 13 |
14 | 15 | 16 | -------------------------------------------------------------------------------- /this.js: -------------------------------------------------------------------------------- 1 | var Colorizer = { 2 | colors: ['red', 'green', 'blue', 'yellow', 'black', 'white'], 3 | bindEvents: function() { 4 | // what's the value of this 5 | var self = this; 6 | $('a.broken').on('click', this.colorize); 7 | $('a.working').on('click', function() { 8 | // what's the value of ? why do we use self? 9 | self.colorize(); 10 | }); 11 | $('a.ajax-broken').on('click', this.ajaxStuffneedThis); 12 | $('a.ajax-working').on('click', function() { self.ajaxStuffneedThis() }); 13 | $('a.ajax-also-working').on('click', this.ajaxStuffdontNeedthis); 14 | }, 15 | 16 | colorize: function() { 17 | // what's the value of when you click a.broken vs a.working? 18 | console.log(this); 19 | var color = this.colors[Math.floor(Math.random()*this.colors.length)]; 20 | $('body').css('background', color); 21 | }, 22 | 23 | ajaxStuffneedThis: function() { 24 | // what's the value of this line 11 vs line 12? 25 | var self = this; 26 | $.ajax({ 27 | url: 'https://api.github.com/users/edshadi', 28 | type: 'GET' 29 | }).done(function(data) { 30 | self.appendUser(data); 31 | }) 32 | }, 33 | 34 | ajaxStuffdontNeedthis: function() { 35 | // don't need a reference to Colorizer object, so this works fine. 36 | // what's the value of this? 37 | var self = this; 38 | $.ajax({ 39 | url: 'https://api.github.com/users/edshadi', 40 | type: 'GET' 41 | }).done(function(data) { 42 | $(this).siblings('.data').append(data.url); // will not work 43 | $(self).siblings('.data').append(data.url); // will work 44 | }) 45 | }, 46 | 47 | appendUser: function(data) { 48 | $('.data').append(data.url) 49 | } 50 | 51 | 52 | } 53 | 54 | $(document).ready(function() { 55 | Colorizer.bindEvents(); 56 | }); 57 | --------------------------------------------------------------------------------