Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active August 3, 2023 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vxhviet/2473c95004c4bd4d40b7d296071230a6 to your computer and use it in GitHub Desktop.
Save vxhviet/2473c95004c4bd4d40b7d296071230a6 to your computer and use it in GitHub Desktop.

[JavaScript] - Object.create()

SOURCE

// Basically this is a way to link a prototype to any object that we want.

// the prototype
const PersonProto = {
  calcAge() {
    console.log(2037 - this.birthYear);
  },

  // the name can be anything, doesn't need to be `init`
  init(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  },
};

const steven = Object.create(PersonProto); // link `steven` to the prototype
console.log(steven);
// manually assign the properties
steven.name = 'Steven';
steven.birthYear = 2002;
steven.calcAge();

console.log(steven.__proto__ === PersonProto); // true

const sarah = Object.create(PersonProto);
// better way to assign the properties.
// This has nothing to do with constructor function as there is no `new` keyword.
sarah.init('Sarah', 1979);
sarah.calcAge();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment