You have two options here:
1) use a temporary variable to store the object's reference:
do: function() {
var self = this;
$.getJSON('getcolour.php', function(resp) {
if (resp.colour == self.colour) { ... }
});
};
If you choose this way, you have both "local this
" (as getJSON handler context object) and "object this
" easily available in your handler. But you have, of course, to define that temporary variable. self
is one of the most common names usually chosen for this purpose, but it actually can be any identifier available - as long as it doesn't overlap with other variables' names).
2) use the function made right for this: $.proxy
do: function() {
$.getJSON('getcolour.php', $.proxy(function(resp) {
if (resp.colour == this.colour) { ... }
}, this));
};
With this approach you have replaced the context object of the handler - it now points to this
(as an object which defines do
function).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…