linepisode
linepisode

Reputation: 65

Accesing function's variable from another function

I have a function in my object.

I want to access this function's variable from another function.Can anyone help me?

Here is my sample code. Any help would be greatly appreciated. Thanks.

var drops=  {
    hoverClass: "hoverme",
    greedy: true,
    accept: "#mini",
    drop: function(event,ui){
        var droppedOn2 = $(this);
        var dropped2 = $(ui.draggable);
        alert(droppedOn2.attr('id')); alert(dropped2.attr('id'));
        $(dropped2).appendTo(droppedOn2).draggable();

    },
    over: function(event, ui){
        console.log("buraya geliyorum > " + this.id);
    } 
};


$('#hebelek').sortable({
    connectWith: '#hebelek',
    cursor: 'pointer'
    }).droppable({
        accept: '#gridIcon1-2, #gridIcon2-2, #widgetIcon',
        activeClass: 'highlight',
        drop: function(event, ui) {
            var ilk = drops.droppedOn2;
            var droppedOn = $(this);
            var dropped = $(ui.draggable).clone();
            var fileName = dropped.attr('id');
            alert(droppedOn.attr('id')); alert(fileName);
            if (fileName == "gridIcon1-2"){   
               $(grid1_2Div).appendTo(droppedOn).find('.gridcell').droppable(drops)
            };

            if (fileName == "gridIcon2-2") {
               $(grid2_2Div).appendTo(droppedOn).find('.gridcell').droppable(drops)
            };

            if ((fileName == "widgetIcon") && (droppedOn.attr('id') == "hebelek")) {
               $(widgetDiv).appendTo("I WANT TO USE DROOPEDON2 ON HERE")
    };
    }

});  

Upvotes: 0

Views: 126

Answers (3)

mim
mim

Reputation: 41

To make a variable calculated in function A visible in function B, you have three choices:

  1. make it a global,
  2. make it an object property, or
  3. pass it as a parameter when calling B from A.
 

    function A()
    {
        var rand_num = calculate_random_number();
        B(rand_num);
    }

    function B(r)
    {
        use_rand_num(r);
    }

Upvotes: 0

Dziad Borowy
Dziad Borowy

Reputation: 12579

Create a common scope for both functions (function wrapper will do), and create a variable in the same scope, like so:

(function () {
    var x = 5,
    f1 = function(){
        console.log(x);
    },
    f2 = function(){
        console.log(x);
    };

})();

Upvotes: 1

Max
Max

Reputation: 8836

You cannot. Variables are scoped to the function in which they are declared. If you want to access a variable from two different functions you can declare it outside of both functions and access it from within them. For example:

var sharedVariable = 'something';
function a() {
     sharedVariable = 'a';
}
function b() {
     alert(sharedVariable); 
}

Upvotes: 0

Related Questions