简体   繁体   中英

Are javascript object variables just reference type?

如果您有一个作为对象的javascript变量,并且使新变量等于第一个变量,那么它会创建该对象的新实例,还是它们都引用了同一对象?

They always reference the same object. We can see that by trying the following:

var x = {foo:11};
var y = x;
y.foo = 42;
console.log(x.foo);
// will print 42, not 11

Both will refer to the same object. If you want to create a new instance:

    var Person = function() {
      this.eyes = 2,
      this.hands = 2
    };    

    var bob = new Person();
    var sam = new Person();

Those two are different objects.

Here is the answer: when you create an object and then assign it to another it will refer to the same object.

Here is an example:

var hacker = {
  name : 'Mr',
  lastname : 'Robot'
};

console.log(hacker.name + '.' + hacker.lastname);
// Output Mr.Robot

// This variable is reference to hackers object
var anotherPerson = hacker;

console.log(anotherPerson.name + '.' + anotherPerson.lastname);
// Output Mr.Robot

// These will change hacker object name and lastname
anotherPerson.name = 'Elliot';
anotherPerson.lastname = 'Alderson';

console.log(anotherPerson.name + ' ' + anotherPerson.lastname);
// Output "Elliot Alderson"

// After it if you try to log object hacker name and lastname it would be:
console.log(hacker.name + '.' + hacker.lastname);
// Output "Elliot Alderson"

You can check the link here and play with it. It is not to complicated. JSBIN Object Hacker

Object Reference explained!

Look the image for better understanding. When you create an object, suppose s1 it is having just a reference in the memory heap and now when you create another object say s2 and say s1 = s2 that means both the objects are actually pointing to the same reference. Hence when you alter either of them, both change.

对象参考示例

If you mean something like this

var a = { foo: "foo" };
var b = a;

then yes. They reference the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM