1

I'm creating the script files for my Project using Object Orientation and I also use frameworks/widgets like jQuery and Datatables.

The public properties I create on my class, are not accessible from the inner scope of functions that are executed from jQuery code.

Here is a sample:

    function MyClass() {
        this.MyProperty = '';
    }

    MyClass.prototype.initialize = function() {
            $(document).ready(function(){
            alert(this.MyProperty); // MyProperty is undefined at this point
        }
    };

How can I fix this? Is this the correct way to have a property that can be accessed from every member of a class?

1
  • 2
    What do you want to achieve with all that? Commented Nov 4, 2012 at 1:55

4 Answers 4

4

store this :

 function MyClass() {
        this.MyProperty = '';
    }

    MyClass.prototype.initialize = function() {
            var that=this;
            $(document).ready(function(){
            // in event handler regardless of jquery this points 
            // on element which fire event. here this === document,
            alert(that.MyProperty); // MyProperty is defined at this point
        }
    };
Sign up to request clarification or add additional context in comments.

Comments

0

That is because this does not point to your class but to the document in that function. You need to store what it points to, when it points to your class:

function MyClass() {
    this.MyProperty = '';
}

MyClass.prototype.initialize = function() {
    var myClassInstance=this;
    $(document).ready(function(){
        alert(myClassInstance.MyProperty); // Will contain the property
    });
}

Comments

0

$.proxy can help with this,

function MyClass() {
    this.MyProperty = '';
}

MyClass.prototype.initialize = function() {
    $(document).ready($.proxy(function(){
        alert(this.MyProperty);
    },this));
};

Comments

0

This is a little different from the others, but a little easier to work with. Keeps the logic of assigning the "this" context outside of the initialize() function itself. Your unique case could nullify this solution from being viable, but thought I'd share anyway.

function MyClass() {
   this.MyProperty = '';
   $(function(){
      this.initialize();
   }.call(this));
}

MyClass.prototype.initialize = function () {
   alert(this.MyProperty);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.