关于java及javaScript中值传递和引用传递

2019-08-06  本文已影响0人  SmileMylife

此处需要特别声明的是:java和javaScript中只存在值传递。

java中测试代码如下:

package test.test;

/**
 * Created by ZhangPei on 2018/8/21.
 */
public class TestYinYong {
    public static void main(String[] args) {
        Person person = new Person();
        test(person);
        System.out.println(person.getUsername());
    }

    public static void test(Person person) {
        person.setUsername("zhagpei");
        person = new Person();
        person.setUsername("zhangxu");
    }

}

class Person {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
image.gif

javaScript中测试代码如下:

/**
 * Created by ZhangPei on 2018/8/21.
 */
function valueCopy(obj) {
    obj.username = "zhangpei";
    obj = new Object();
    obj.username = "zhangxu";
    console.log(obj.username);
}

var obj1 = new Object();
valueCopy(obj1);
console.log(obj1.username);
image.gif

从上述代码可以看出,两者都只存在值传递。

上一篇下一篇

猜你喜欢

热点阅读