0

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
        }
     }

}

1
  • Not that the usual convention for class names is to have them capitalized (i.e. Person, not person). Commented Dec 19, 2014 at 8:11

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

this isn't "inherited", it's set by how the function is called.
@RobG - agreed, poor choice of words.
Thanks Sten Muchow. Makes perfect sense.
1

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);
        }
     }
}

Comments

Your Answer

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.