Skip to main content

Posts

Showing posts with the label this

jQuery/JavaScript "this” pointer confusion

The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element? // a class with a method function foo() { this.bar(); // when called here, "this" is the foo instance var barf = this.bar; barf(); // when called here, "this" is the global object // when called from a click, "this" is the html element $("#thing").after($("<div>click me</div>").click(barf)); } foo.prototype.bar = function() { alert(this); } Source: Tips4all

this.function is not a function error, but function exists

I have some code to get calendar events and display them. The display is only updated if the events have changed, since the last call. var calendar = { events = null, display_calendar_events : function (data) { // Some display stuff... }, get_events: function() { // Get messages for calendar $.getJSON("/ajax/get-events/", function(json){ var new_events = json.data; // If events haven't changed, do nothing if (this.events === new_events) { return true; } // Events have changed. // Save new events this.events = new_events; // Display new events this.display_calendar_events(json); }); }, } I call this with: calendar.get_queued_events(); The problem is, I'm getting the error "this.display_calendar_events is not a function" (last line of code). But if I change this line to: calendar.d

JavaScript "this" confusion

This is probably pretty easy, yet I am confused, so maybe I might still learn something more today. I am trying to do the following: var myObj = {}; myObj.src = {} myObj.src.A = ['1.png','2.png','3.png']; myObj.A = new Image(); myObj.A.src = this.src.A[0]; This will result in an Uncaught TypeError: Cannot read property 'A' of undefined error. When I use myObj.src.A[0] instead of this it is working fine. What would be the correct way to use this in this context?