Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class members from nested functions

Tags:

javascript

oop


i have this class in javascript

var MyGird = Class.extend({
  classMemeber1 : "Some Value"
  ,clickEvent : function(){
        this.editor.on({
            afteredit: function() {
                //
                //  HOW TO I ACCESS classMemeber1 from here? ?
                //
                //
            }
        })
})

how do i access classMemeber1 from inside of afteredit...
Thanks

like image 824
fatnjazzy Avatar asked Oct 16 '10 17:10

fatnjazzy


1 Answers

You need to save a reference to the object invoking clickEvent function by storing this [1] in a variable. It will be available inside the afteredit method because of closure.

var MyGird = Class.extend({
    classMemeber1: "Some Value",
    clickEvent: function () {
        var self = this; // save object reference
        this.editor.on({
            afteredit: function () {
                // access classMemeber1 from here
                // by using the stored reference
                alert(self.classMemeber1);
            }
        });
    },
    // ...
});

[1] this operator in javascript (note: 'this' is not an operator)

like image 82
25 revs, 4 users 83% Avatar answered Sep 21 '22 08:09

25 revs, 4 users 83%