?
Solved

pass by reference?

Posted on 2006-05-18
2
Medium Priority
?
6,870 Views
Last Modified: 2011-08-18
I'm looking for a way to pass a variable by reference/pointer, like you can do in C.  Is there a way to do this in javascript?  

I've read that you basically can't do that, but javascript does pass objects and arrays by reference, right?  It just doesn't pass plain data like integers by reference.

I was thinking that if I need to pass an integer value by reference, I'd need to create an object, like:

function integerHolder(num) {
   this.integer = num;
}

And then pass a refernece to an instance of integerHolder, where it could be modified, like:

var myInt = new integerHolder(10);
changeNumber(myInt);

Is that the only way to do this, or is there some simpler way?
0
Comment
Question by:chsalvia
2 Comments
 
LVL 49

Accepted Solution

by:
Roonaan earned 1000 total points
ID: 16712884
var myInt = {num:10};
changeNumber(myInt)

function changeNumber(intObj) {
  intObj.num = 11;
}

-r-
0
 
LVL 10

Expert Comment

by:Dennis Maeder
ID: 16713421
For the record, this html snippet illustrates the case for value (v) and reference (r) together

<script type='text/javascript' language='javascript'>
var r={num:2};
var v=fn(r);
function fn(v) {
  v.num=2*v.num;
  return v.num;
}
document.write("r "+r.num+"<br>v "+v)
</script>

D
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question