jQuery: how to access parent function “this” from inside anonymous function?

前端 未结 5 873
余生分开走
余生分开走 2020-12-28 16:07
...
$.fn.annotateEdit = function(image, note) {
    if (note) {
        this.note = note;
    } else {
        var newNote = new Object();
        newNote.id = \"new         


        
相关标签:
5条回答
  • 2020-12-28 16:18

    You can bind the context of the parent object like so.

    form.find(':radio').change(function(that) {
        var vacancy = $(this).attr('value');
        that.note.vacancy = vacancy;
    }.bind(null,this));
    
    0 讨论(0)
  • 2020-12-28 16:24

    There is no dedicated language mechanism for it. The common pattern is to store the this in local (closure) variable (often named self or that) of the outer function:

    var self = this;
    var innerFunction = function() {
        self.x = 1;
    };
    
    0 讨论(0)
  • 2020-12-28 16:31

    Check this - http://api.jquery.com/bind/ and "Passing event data" You can do something like this :

    form.find(':radio').bind("change", {
    context : this
    }, function(event){
        console.log(event.data.context);
        console.log(event.data.context.note);
    });
    
    0 讨论(0)
  • 2020-12-28 16:32

    I use a pattern like this so I can access anything in the enclosing scope:

    var that = this;
    ...
    
    form.find(':radio').change(function () {
        that.note.vacancy = $(this).attr('value');
    });
    

    I am a fan of this pattern because it makes the code a little more readable. In my opinion, it is clear what it being accessed is part of the enclosing scope (as long as the usage of that is consistent).

    0 讨论(0)
  • 2020-12-28 16:37

    Use $.proxy to bind it to a function...

       // Returns a function-------v
    form.find(':radio').change( $.proxy(function() {
    
        var vacancy = $(this).attr('value');
        mynote.vacancy = vacancy;
    
    }, this) );
    //   ^---- ...that has its "this" value set as this argument.
    
    0 讨论(0)
提交回复
热议问题