先看题1
var obj = {name:"a"
} function bar(obj) { console.log(obj.name); obj = {name:"b"
}; console.log(obj.name) } console.log(bar(obj)) console.log(obj.name)在chrome控制台执行以下看看,发现依次打印
aba函数体内重新赋值了,新开辟了内存区域,跟外面的引用类型无关了。
题2,稍微有点变化
var obj = {name:"a"} function bar(obj) { console.log(obj.name); obj.name = "b"; console.log(obj.name) } console.log(bar(obj)) console.log(obj.name)
在chrome控制台执行以下看看,发现依次打印
a b b引用类型值发生改变了
题3,再稍微变化一下
var obj = {name:"a"} function bar(obj) { console.log(obj.name); var obj = {name:"b"}; console.log(obj.name) } console.log(bar(obj)) console.log(obj.name)
在chrome控制台执行以下看看,发现依次打印
a b a
题4,继续变化
var obj = "name"function bar(obj) { console.log(obj); var obj = "age"; console.log(obj) } console.log(bar(obj)) console.log(obj)
发现以此打印
name age name
题5,继续变化
var obj = "name"function bar() { console.log(obj); var obj = "age"; console.log(obj) } console.log(bar(obj)) console.log(obj)
发现依次打印
undefined age name
题6,还是继续变化
var obj = "name"function bar() { console.log(obj); obj = "age"; console.log(obj) } console.log(bar(obj)) console.log(obj)
瞧瞧这次又会打印啥
name age age
如果你都答对了,说明 你理解了引用传递和值传递 ,理解了局部变量和全局变量,如果你答错了,好好想想估计也就想通了!!
该贴由koei123转至本版2015-7-14 11:14:18