Home > OS >  Object prototype is copied or referenced in JavaScript?
Object prototype is copied or referenced in JavaScript?

Time:08-07

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 ?

CodePudding user response:

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);

CodePudding user response:

Inheriting. might be the word to go https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

  • Related