0

I'm starting learning OOP in javascript and got stuck with this problem. I have simple object:

function Notifications() {
 this.button = $('#dLabel');
 this.wrapper = $('#notifications');
 this.elements = [];
}
Notifications.prototype = {
 constructor: Notifications,
 fetch: function() {
 $.ajax({
 method: "GET",
 url: '/notifications.json'
 }).done(function(data) {
 this.elements = data;
 this.refresh();
 });
 },
 refresh: function() {
 console.log("REFRESH");
 }
}
$(function() {
 var ns = new Notifications();
 ns.fetch();
})

When I run this I get:

Uncaught TypeError: this.refresh is not a function

Is it becasue this in .done function is not Notifications instance? How can I fix this ?

asked Mar 18, 2016 at 12:04
1
  • this in function in done() will be refer to the global object Commented Mar 18, 2016 at 12:09

1 Answer 1

3

Use the bind() method to fix the context:

Notifications.prototype = {
 constructor: Notifications,
 fetch: function() {
 $.ajax({
 method: "GET",
 url: '/notifications.json'
 }).done(function(data) {
 this.elements = data;
 this.refresh();
 }.bind(this)); // <------- Use bind(this)
 },
 refresh: function() {
 console.log("REFRESH");
 }
}

The done() handler function(data) {...} is executed as a simple function invocation, which has the context this as the global object (Window) or undefined in "strict mode".
The Function.prototype.bind(newContent) modifies the context to newContext.

This section describes in more details how this can be lost and how to prevent that.

answered Mar 18, 2016 at 12:07
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.