Skip to content
Advertisement

Object prototype is copied or referenced in JavaScript?

In the following code :

let user = {
  name: "John",
  surname: "Smith",

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  },

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

let admin = {
  __proto__: user,
  isAdmin: true
};

alert(admin.fullName); // John Smith (*)

// setter triggers!
admin.fullName = "Alice Cooper"; // (**)

alert(admin.fullName); // Alice Cooper, state of admin modified
alert(user.fullName); // John Smith, state of user protected

The user Object is the prototype of admin Object, As we see line (**) sets the fullName for admin Object, although user Object remains the way it was.

So is it correct to say that user Properties & Methods are copied to admin Object ?

Advertisement

Answer

Using Object.getOwnPropertyNames reveals that by using admin.fullName = "Alice Cooper" you actually create new properties instead of overriding anything.

let user = {
  name: "John",
  surname: "Smith",

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  },

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

let admin = {
  __proto__: user,
  isAdmin: true
};

console.log(Object.getOwnPropertyNames(admin));
admin.fullName = "Alice Cooper";

console.log(Object.getOwnPropertyNames(admin));
console.log(Object.getOwnPropertyNames(user));

Changing the the properties of the prototype reveals that it’s references

let user = {
  name: "John",
  surname: "Smith",

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  },

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

let admin = {
  __proto__: user,
  isAdmin: true
};

console.log(admin);
user.fullName = "Alice Cooper";

console.log(admin);
console.log(user);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement