Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a variable by ref reference in javascript

Tags:

javascript

I have a scope variable which has false value by default.

I want when I pass this variable to a function to modify it's value to true.

but this can't be done since the passage of params in JavaScript is by value.

this is a simple code of what I'm tryin to do:

myapp.controller('PersonCtrl', function ($scope) { 
    $scope.step = false;
    change($scope.step);
    console.log($scope.step);
});

change = function(step){
  step = true;
}

jsfiddle:

http://jsfiddle.net/SNF9x/177/

how can I solve this ?

like image 597
Renaud is Not Bill Gates Avatar asked Jan 07 '23 05:01

Renaud is Not Bill Gates


2 Answers

You can pass the object holding the primtive to your change function:

myapp.controller('PersonCtrl', function ($scope) { 
    $scope.step = false;
    change($scope);
    console.log($scope.step);
});

change = function(obj){
  obj.step = true;
}

You could event pass the name of the variable you want to change:

myapp.controller('PersonCtrl', function ($scope) { 
    $scope.step = false;
    change($scope, 'step');
    console.log($scope.step);
});

change = function(obj, prop){
  obj[prop] = true;
}
like image 51
Nick D Avatar answered Jan 08 '23 19:01

Nick D


You can't pass variables by reference in JS, but you can pass objects by reference and then modify the properties, like this...

myapp.controller('PersonCtrl', function ($scope) { 
    $scope.step = false;
    change($scope);
    console.log($scope.step);
});

change = function($scp){
  $scp.step = true;
}

jsfiddle:

http://jsfiddle.net/SNF9x/178/

like image 31
Reinstate Monica Cellio Avatar answered Jan 08 '23 20:01

Reinstate Monica Cellio