LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   What sense does this make (Javascript)? (http://www.linuxquestions.org/questions/programming-9/what-sense-does-this-make-javascript-848151/)

resetreset 12-03-2010 09:40 AM

What sense does this make (Javascript)?
 
Quoting from my Javascript book:

(for function arguments):
Scalar arguments are passed by value, which means that a copy of the argument is made for processing in the function, and changes to the argument in the function won't be reflected back to the calling program. Objects though, are passed by reference: any changes to them in the function are reflected in the calling program.


What sense does this make? Why have they done this?

tsg 12-03-2010 12:58 PM

It actually ends up making more sense when you understand what's going on. When you pass a scalar value, it only passes the value. When you pass an Object, you are actually passing a reference to the object, which won't be changed by the function. The object the reference points to, though, can be changed. It's a lot like passing pointers to variables in C except that Java hides some of the details. It also doesn't do what you think it will a lot of times. For instance:

Code:

public void myMethod1(String s) {
    s = new String("This is a new String");
}

public void myMethod2() {
    String t = new String("This is the first String");
    System.out.println(t);
    myMethod1(t);
    System.out.println(t);
}

will print:
Code:

This is the first String
This is the first String

because myMethod1 is making s point at a new String object rather than changing the object s references. Because the parameters are passed by value, t in myMethod2 is not altered.

On the other hand, if we do this instead:

Code:

public void myMethod1(StringBuffer s) {
    s.append(" This is a new String");
}

public void myMethod2() {
    StringBuffer t = new StringBuffer("This is the first String");
    System.out.println(t);
    myMethod1(t);
    System.out.println(t);
}

we'll get this output:

Code:

This is the first String
This is the first String This is a new String

because the Object t points to is being altered, not t itself.

gd2shoe 12-03-2010 11:29 PM

Java != JavaScript
JavaScript is a misnomer.

(I believe the answer is the same, but your examples include syntax he may be unfamiliar with.)

paulsm4 12-04-2010 01:16 AM

Quote:

Q: What sense does this make? Why have they done this?
A: Because (if you stop to think about it), it's the ONLY approach that makes sense. Unless you want to add "copy constructors" (and everything that goes with it) to Javascript :)

PS:
"Javascript" is emphatically NOT "Java", as gd2shoe already pointed out. But in this instance, they happen to behave similarly.


All times are GMT -5. The time now is 02:02 PM.