10


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

Joe Frambach
  • 26,300
  • 10
  • 69
  • 98
fatnjazzy
  • 5,840
  • 11
  • 54
  • 82

2 Answers2

36

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)

Community
  • 1
  • 1
gblazex
  • 47,726
  • 12
  • 95
  • 89
8

If you write ES6, you can use arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

In your example, should be something like (not tested):

var MyGird = Class.extend({
    classMemeber1: "Some Value",
    clickEvent: () => {
        this.editor.on({
            afteredit: () => () {
                alert(this.classMemeber1);
            }
        });
    },
    // ...
});
Nico Toub
  • 1,168
  • 13
  • 14