this
does not work like it does in other languages. When not inside a function (think global space) this
refers to the Window
object of the current browser. By default, new functions are created as children of Window
.
For example;
function foo() {
return this;
}
Is actually the same as Window.foo = function() { return this; }
(unless browser is in strict mode).
So when you call foo()
the following is true.
foo() === window; // True, because foo() returns this which is window.
Since by default this
refers to the object the function is bound to. You can change the default value of this
by binding the function to a different object.
var o = {
x: 99,
foo: function() {
return this.x;
}
};
console.log(o.foo()); // will output 99
It doesn't matter when you bind the function to an object. As in this example.
var a = {
x: 99
};
var b = {
x: 77
};
function foo() {
return this.x;
}
a.f = foo;
b.f = foo;
console.log(a.f()); // will output 99
console.log(b.f()); // will output 77
In the above example the function foo
is the same, but this
changes depending on which bound object reference was used to call it.
So what is going on with DOM events?
The function is bound to the DOM element, and that's a Javascript object. So this
refers to the object that triggers the event. Even if the same function is bound to multiple elements. this
always refers to the one that triggered the function.
So now back your source code and problem. Your using this
inside the .done(function(msg){....})
function. jQuery has bound the ajax
object to the function so that this
refers to that object.
You can change what this
refers too by using the bind()
function. bind
lets you change what object is bound to the function so that this
refers to that object instead.
$('p').click(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "http://www.example.com/change_notification.php"
}).done(function( msg ) {
$("#changed_notification_value").text( msg );
var n_url = $('a', this).attr('href');
window.location.href = n_url;
}.bind(this));
});
Above, I didn't change your source code but just added .bind(this)
to the end of your function(msg){...}.bind(this)
. The object this
refers to outside the function is the DOM element that triggered the event, and by binding it to your callback function for done
your source code should now work.
the value of n_url shows undefined
$('a', this)
returns anything