-2

In JavaScript I created an User class. I wrote a method(function) to this, but i can't give a return statement. Here is my class:

function User() {
    var isLogedIn = "FukkaMukka";
    var mail = "";
    var name = "";

    //functions

    this.isLogedInFn = function(callback) {
        $.post("controller.php?module=login&action=test", function(e) {
            this.isLogedIn = false; // Here i can't reach the object variable.. why?
            return e;
        })
    }
    this.logIn = logIn;

}
tthlaszlo
  • 435
  • 2
  • 7
  • 14
  • possible duplicate of [Variable Scope: this.remove is not a function](http://stackoverflow.com/questions/3754273/variable-scope-this-remove-is-not-a-function) – JJJ Apr 19 '12 at 18:01
  • 2
    I am surprised nobody else has said this, but ... **return inside $.post is useless** because it runs "asynchronously". Also, `isLoggedIn` is the correct spelling ;-) –  Apr 19 '12 at 18:05
  • 1
    Oh, also I am "closing as not a real question" because no details of *what the actual problem* is were given, and no *specific question* about this issue was asked. If they were, it could be identified as one of the million duplicates :( –  Apr 19 '12 at 18:08

2 Answers2

1

The callback is not executed in the context of your object. Several ways to work around:

  • call jQuery.ajax with the context parameter
  • bind() your function to your object
  • store a reference to your object in a variable use that (like Sarfraz suggested)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0
function User() {
    var isLogedIn = "FukkaMukka";
    var mail = "";
    var name = "";
    var self = this;
    //functions

    this.isLogedInFn = function(callback) {
        $.post("controller.php?module=login&action=test", function(e) {
            // `this` is no longer in the scope of the function as you would think it would be. in this case `this` iirc will reference the window object.
            self.isLogedIn = false; 
            return e;
        })
    }
    this.logIn = logIn;

}

see comments in code.

rlemon
  • 17,518
  • 14
  • 92
  • 123