标签:
正读 JavaScript: The Good Parts.
1. 通过反射和遍历,访问对象的所有属性。
<html>
<body>
<script type="text/javascript">
var x = {
"first-name": "Gift",
"last-name" : "Young"
};
x.nickname = ‘nick‘;
for(name in x){
document.writeln(name+":"+x[name]+" "+typeof x[name]+"<br>");
}
</script>
</body>
</html>
上述代码的运行结果是:
first-name:Gift string
last-name:Young string
nickname:nick string
2. " Objects are passed around by reference. They are never copied. "
下面的试验证实,String是按值复制的。
x与stooge是同一对象的reference,所以它们的属性的值一起变化;
snick和xnick的值“来自”对象的属性,但是snick和xnick的值并不随对象的属性的值的变化而变化。
<html>
<body>
<script type="text/javascript">
var stooge = {
"first-name": "Gift",
"last-name" : "Young"
};
var x = stooge;
x.nickname = ‘before‘;
var snick = stooge.nickname;
var xnick = x.nickname;
document.writeln("nick:"+stooge.nickname+"<br>");
document.writeln("x.nickname:"+x.nickname+"<br>");
document.writeln("xnick:"+xnick+"<br>");
document.writeln("snick:"+snick+"<br>");
document.writeln("<br>");
x.nickname = ‘after‘;
document.writeln("nick:"+stooge.nickname+"<br>");
document.writeln("x.nickname:"+x.nickname+"<br>");
document.writeln("xnick:"+xnick+"<br>");
document.writeln("snick:"+snick+"<br>");
</script>
</body>
</html>
上述代码的运行结果是:
nick:before
x.nickname:before
xnick:before
snick:before
nick:after
x.nickname:after
xnick:before
snick:before
笔记:javascript通过反射和遍历,访问对象的所有属性,及 按引用/按值传递
标签:
原文地址:http://blog.csdn.net/younggift/article/details/43419113