开发者

Why does this Javascript example copy the variable value instead of pass by reference?

In Javascript The Good Parts, it states:

Why does this Javascript example copy the variable value instead of pass by reference?

So I would expect the following code example to output 1001 since "objects are never copied but passed around by reference", so why does it output 0000?

var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';

$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"

Added:

@Gareth @David, tha开发者_JS百科nks, this is what I was trying to show in this example, works:

var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';

$('p#test').html(page_item.access_groups.developer); //is '1001'


Don't think of pass-by-reference in the C++ context, because it's not the same.

var member = page_item.access_groups.member // Sets member to this value
member = '1001'; // Now sets it to another value

If there was a method on strings which changed them, then this:

member.removeLastLetter();

would alter page_item.access_groups.member. However, with your = you are changing the variable's reference, not the object it previously referenced


Because page_item.access_groups.member is a string and not an Object.


This is probably getting bashed by JS-Gurus but basically it goes down like this:

Objects are passed by reference.
Strings (numbers, etc... basically 1 dimensional variables) are passed by value.

I did try and understand the lengthy explanations on data types but I seriously needed some work done and haven't gotten time to look at it more closely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜