Codex73
Codex73

Reputation: 5766

Variable access within object scope

How can I access the values of "runit" and "property2"?

$("#selector").draggable({
    property1: "myvalue",
    property2: "myvalue",
    property3: "myvalue",
    start: function() {
        var runit = 'one value';
    },
    stop: function(){                       
        //Access Value of runit
        //Acess Value of property2
    }
});

Upvotes: 1

Views: 85

Answers (3)

Phil
Phil

Reputation: 164746

You can't access runit from stop() as it is scoped only to the start() method. You should be able to access property2 with

this.property2

You could add runit to the object's properties, eg

{
    property1: "myvalue",
    property2: "myvalue",
    property3: "myvalue",
    runit:     null,
    start: function() {
        this.runit = 'one value';
    },
    stop: function(){
        console.log(this.runit);
        console.log(this.property2);
    }
}

A possibly working example - http://jsfiddle.net/9rZJH/

Upvotes: 4

elclanrs
elclanrs

Reputation: 94101

Another option is to just return runit. I mean, it all depends on what you want to accomplish:

start: function() {
    var runit = 'one value';
    // Stuff
    return { runit: runit };
},
method: function(){
    var foo = this.start().runit;
}

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108490

In order to access runit you need to define it outside the object’s scope:

var runit;

$("#selector").draggable({
    property1: "myvalue",
    property2: "myvalue",
    property3: "myvalue",
    start: function() {
        runit = 'one value';
    },
    stop: function(){                       
        //Access Value of runit
        console.log(runit);
        //Acess Value of property2
        console.log(this.property2);
    }
});

property2 should be accessible via this.property2 but that depends on how the stop method is called internally.

Upvotes: 2

Related Questions