0


I have this:

function test1()
{
    this.count = 0;
    this.active = 0;
    this.enable = function () {this.active = 1;}
    this.disable = function () {this.active = 0;}
    this.dodo = function ()
                {
                    $("html").mousemove(function(event) {
                        // I want to get here the "active" param value;                 
                    });
                }
    this.enable();
    this.dodo();
}

instance = new test1();
instance.disable();

Let's say I want to check the active param of the test1 class in the commented place. How can I get it there ? Thanks!

3 Answers 3

2

If you want access to all the member variables of the higher scope, you just need to save the this pointer from that scope into a local variable so you can use it inside the other scope:

function test1() {
    this.count = 0;
    this.active = 0;
    this.enable = function () {this.active = 1;}
    this.disable = function () {this.active = 0;}
    var self = this;
    this.dodo = function () {
        $("html").mousemove(function(event) {
            // I want to get here the "active" param value;                 
            alert(self.active);
        });
    }
    this.enable();
    this.dodo();
}

instance = new test1();
instance.disable();
Sign up to request clarification or add additional context in comments.

Comments

1
this.dodo = function ()
            {
                var active = this.active;

                $("html").mousemove(function(event) {
                    alert(active);             
                });
            }

Comments

1

When you call a function 'this' refers to the object the function was invoked from, or the newly created object when you use it together with the keyword new. For example:

var myObject = {};
myObject.Name = "Luis";
myObject.SayMyName = function() {
    alert(this.Name);
};

myObject.SayMyName();

Note in JavaScript there are multiple ways to declare, define, and assign fields and methods to objects, below is the same code written more similarly to what you wrote:

function MyObject() {
    this.Name = "Luis";
    this.SayMyName = function() {
        alert(this.Name);
    };
}

var myObject = new MyObject();
myObject.SayMyName();

And yet another way to write the same thing:

var myObject = {
    Name: "Luis",
    SayMyName: function() {
        alert(this.Name);
    },
};

myObject.SayMyName();

There are also several different ways to invoke a function.

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.