Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - jquery reference this from parent

Google is not being helpful trying to find the answer to this question! :(

How do I properly reference this.colour from the parent object from within a jQuery function like this:

var obj = {
 colour: 'blue',
 do: function() {
  $.getJSON('getcolour.php', function(resp) {
    if (resp.colour == this.colour) { //<== this.colour doesnt = blue
     //match
    }
  });
 }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...