Skip to content

Instantly share code, notes, and snippets.

@cristinafsanz
Last active August 23, 2023 15:24
Show Gist options
  • Select an option

  • Save cristinafsanz/8d5344552296ddab7187587f4389d777 to your computer and use it in GitHub Desktop.

Select an option

Save cristinafsanz/8d5344552296ddab7187587f4389d777 to your computer and use it in GitHub Desktop.

Same as:

john: {
  firstname: "John",
  lastname: "Doe",
  greet: function() {
    return `Hi ${this.firstname}`
  }
}

With classes:

class Person {
  constructor(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname
  }
  
  greet() {
    return `Hi ${this.firstname}`
  }
}

const john = new Person("John", "Doe")

class InformalPerson extends Person {
  constructor(firstname, lastname) {
    super(firstname, lastname)
  }
  
  greet() {
    return `Yo ${this.firstname}`
  }
}

Constructor function

function Person(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
}

const john = new Person("John", "Doe");

Convention: with capital letter (not to forget "new")

When creating with "new", you can use prototype to add methods (outside the constructor, to have it only once, not for each object):

Person.prototype.getFullName = function() {
  return `${this.firstname} ${this.lastname}`
}

john.getFullName();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment