What's going on in the background with regard to this JavaScript?

I was reviewing some today, when I encountered the following convention : TestParam(1); function TestParam(p){ var p = p + 1; alert(p); // alerts '2' } Now, obviously, the developer didn't mean to delcare 'p' within the function, instead maybe meaning: p = p + 1; But the code still worked, i.e. the value alerted was "2". So it got me to thinking. What would happen in the following scenario: var a = 1; TestParam(a); alert(a); // alerts "1" function TestParam(p){ var p = p + 1; alert(p); // alerts '2' } Again the alerts were as I suspected (as intimated in the comments above). So then I was curious as to what would happen if I used an object: var a = { b: 1 }; TestParam(a); alert(a.b); //alerts 1 function TestParam(p) { var p = {b:p.b + 1}; alert(p.b); //alerts 2 } So, in this instance, JavaScript has 'remembered' the variable `a`, even though when it is passed to TestParam as `p`, `p` is redeclared. Now if I were to have done the following within the function, then both alerts would have been "2" p.b++; //var p = {b:p.b + 1}; I.e. it would have modified the member `b` of the original object. I get this. Its the previous scenario that baffles me! I realise this is quite a hypothetical question that is unlikely to carry much real-world usefulness, but it still made me quite curious, as to what is going on in the background, and how exactly JavaScript is scoping and referencing these variables. Any thoughts?
Are you sure you are correct about last example with alert(p.a) ? Trying to analyze this, gives me an idea that p object which is passed to TesParam has no "a" member in it. alert inside TestParam will give you undefined!

以上就是What's going on in the background with regard to this JavaScript?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏