chrome 下一段代码的理解

记一次 代码理解

//Depending on the browser, the console shows a live link to the object. If you don't expand the object within the console until after the line that adds the .age property runs then when you do expand you'll see that property. Is that what you mean? One way to avoid this is to use console.log("obj1", JSON.stringify(obj)), to log a snapshot of the object at that moment. 
// chrome 开发环境下
var obj = {name:"小明"};
console.log("obj1",obj);
// 1. {name:"小明",age:10}
obj.age = 10;
// 2. {"name":"小明",age:10}
console.log("obj2",obj);

为什么 第一个 log 的结果不是 {name:"小明"}

产生这种结果的原因在于:
1. 浏览器对于 console.log 的行为表现是不一样的
2. 在firefox和 IE11 下的 输出结果和我们预料的一样
3. 在 chrome 下可以通过 JSON.stringify() 函数把 obj对象 “正常” 输出出来
4. 小结: 无论结果如何在 代码中对成员变量的使用都是一致的,符合我们日常的认识。

var obj = {name:"小明"};
if ("age" in obj) {
    console.log("obj1",obj);
}

obj.age = 10;
console.log("obj2",obj);
// {name:"小明",age:10}

所以说,这个现象还是浏览器的 特殊行为

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值