user1233147
user1233147

Reputation: 27

nested function does not recognize javascript "this" keyword

I can't get my nested function to recognize the "this" keyword. Here is an example. I have a constructor function:

function person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.changeName = changename;
}

I have another function with a nested function:

function changeName (name) {
     this.lastname = name;
     $.post("display.php", "some_data", function(data,status) {
        if (status=="success") {
               alert(this.lastName); //undefined
        }
     }

}

Upvotes: 0

Views: 83

Answers (2)

Sten Muchow
Sten Muchow

Reputation: 6711

The function sets this from the inner function you need to either use .bind or the "hack" of that:

function changeName (name) {

     var that = this;

     this.lastname = name;
     $.post("display.php", "some_data", function(data,status) {
        if (status=="success") {
               alert(that.lastName); //undefined
        }
     }
}

Or by using function.protoype.bind.

function changeName (name) {

     this.lastname = name;
     $.post("display.php", "some_data", function(data,status) {
        if (status=="success") {
               alert(this.lastName); //undefined
        }
     }.bind(this))
}

This is a pretty good explanation

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382454

That's because this, in the event handler, is window. You can define an alias in the changeName scope like this :

function changeName (name) {
     var p = this;
     p.lastname = name;
     $.post("display.php", "some_data", function(data,status) {
        if (status=="success") {
               alert(p.lastName);
        }
     }
}

Upvotes: 1

Related Questions