admin管理员组

文章数量:1356908

Sorry for my english. Here is example code:

/**
 * @constructor
 */
function MyNewClass(){
  this.$my_new_button = $('<button>Button</button>');
  this.my_value = 5;

  this.init = function (){
    $('body').append(this.$my_new_button);
    this.$my_new_button.click(
      function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      }
    )
  }
}

How can i access objects my_value property inside jQuery click event function? Is it possible?

Sorry for my english. Here is example code:

/**
 * @constructor
 */
function MyNewClass(){
  this.$my_new_button = $('<button>Button</button>');
  this.my_value = 5;

  this.init = function (){
    $('body').append(this.$my_new_button);
    this.$my_new_button.click(
      function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      }
    )
  }
}

How can i access objects my_value property inside jQuery click event function? Is it possible?

Share Improve this question asked Sep 25, 2013 at 12:20 MaratMSMaratMS 4505 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can do the following

function MyNewClass(){
    this.$my_new_button = $('<button>Button</button>');
    this.my_value = 5;
    var self = this; //add in a reference to this
    this.init = function (){
        $('body').append(this.$my_new_button);
        this.$my_new_button.click(
            function (){
                //This will now alert 5.
                alert(self.my_value);
            }
        );
    };
}

This is a small pattern in javascript (although the name eludes me). It allows you to access top level members of a function within an inner function. In a nested function you can't use "this" to refer to top level members as it will only refer to the function you are within. hence the need to declare the top level functions "this" value into its own variable (called self in this case).

Jquery has a method for that, jQuery.proxy( function, context ):

function MyNewClass(){ 
  this.$my_new_button = $('<button>Button</button>');
  this.my_value = 5;

  this.init = function (){
    $('body').append(this.$my_new_button);
    this.$my_new_button.click(
      $.proxy(function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      },this)
    )
  }
}

DEMO

本文标签: javascriptHow to access to object property inside jQuery event functionStack Overflow