Some languages allow programmers to "pass arguments by reference." In essence, this means that a variable or objects can be sent to a function; and when that variable or object is changed inside of the function, those changes are also made to the original variable or object outside of the function.
Ex. In PHP, you could indicate a pass by reference using an ampersand in the function's parameters:
var $cost = 55;
var $discount = .2;
getDiscountedPriceByValue ($cost, $discount) . "<br />\n";
echo $cost; // OUTPUT WILL STILL BE 55
getDiscountedPriceByReference ($cost, $discount);
echo $cost; // OUTPUT WILL BE 44
function getDiscountedPriceByValue (&$costSent=0, $discountSent=0) {
$costSent = $costSent - ($costSent * $discountSent);
return $costSent;
}
So, does Javascript allow a variable to "pass by reference" like other languages?
As of April 2015:
Only Javascript objects can be passed by reference.
Primitives or simple variables (booleans, strings and numbers) can only be passed by value.
You could put your variable inside of an object as a property, then pass the object to the function. Changes to that object's properties would then be permanent and accessible outside of the function.
Ex.
myValue = 500;
doubleIt(myValue);
window.alert(myValue); // NOTE: Still returns 500, not 1000
function doubleIt (valueSent) {
valueSent = valueSent * 2;
}
myObject = {value:myValue};
doubleItWithObject(myObject);
window.alert(myObject.value); // NOTE: Returns 1000
function doubleItWithObject(objectSent){
objectSent.value = objectSent.value * 2;
}
Or, you could use a variable declared "globally" outside of the function.
Ex.
globalX = 500;
window.alert(globalX); // NOTE: Returns 500
function makeAChange() {
globalX = 1000;
}
makeAChange();
window.alert(globalX); // NOTE: Returns 1000
No comments :
Post a Comment