您的位置:首页 > Web前端 > JavaScript

实例浅析javascript call by value与call by reference

2012-08-13 20:49 609 查看
基本类型是call by value的

var value
= 1;

console.log(value);

func(value);

console.log(value);

function func(val){

val = 3;

console.log(val);

}
输出:
1
3
1

对象和数组call by reference,
即可以修改对象中的属性


var arr_val
= [1,2,3];

var obj_val
= {

width:3,

height:5

};

(obj_val.width ==
3)? console.log('yes'):console.log('no');

(arr_val[2] ==3)? console.log('yes'):console.log('no');

func(arr_val, obj_val);

console.log(arr_val, obj_val);

function func(arr_val, obj_val){

arr_val[2] =100;

obj_val.width =
100;

console.log(arr_val, obj_val);

}
输出:
yes
yes
[1, 2, 100] {width:100, height:5}

[1, 2, 100] {width:100, height:5}
注:由于console.log()输出的是对象最后稳定的值,
故一开始用如上语法

也可以理解为对象和数组call by value的内容是引用
所以可以修改对象的属性,但不能修改引用本身


var arr_val
= [1,2,3];

var obj_val
= {

width:3,

height:5

};

console.log(arr_val, obj_val);

func(arr_val, obj_val);

console.log(arr_val, obj_val);

function func(arr_val, obj_val){

arr_val = [0,0,0];

obj_val = { newAttribute:1 };

console.log(arr_val, obj_val);

}
输出:
[1,2,3] {width:3, height:5}
[0,0,0] { newAttribute:1 }

[1,2,3] {width:3, height:5}

值得注意的是,string类型
是不能改变其值的。
更多javascript字符串的内容,
可以参考javascript: the definitive guide


var str_val
= 'string';

console.log(str_val[0]);

str_val[0] ='a';

console.log(str_val[0]);
输出:
s
s
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: