Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript Working with Classes in JavaScript Adding Methods To Our Class

Adding Methods To A Class.

Why don't we use the word function when creating methods in a class?

3 Answers

Steven Parker
Steven Parker
231,275 Points

You would use "function" if you create methods using the classical (prototype) syntax, which is still available. The new ES2015 "class" syntax doesn't use the word "function" for brevity and also to be more similar to syntax of other languages.

Martin Lecke
Martin Lecke
14,385 Points

You can see the syntax your class as a big blueprint for the objects in creates.

class MyClass {
  constructor(name) {
    this.name = name;
  }
  myMethod() {
    return this.name;
  }
}

const myInstance = new MyClass('Martin');

console.log(myInstance);// ->

{
  name: 'Martin',
  myMethod() {
    return this.name;
  }
}
Ana María Benites Rodríguez
Ana María Benites Rodríguez
1,011 Points

Hi there a couple of questions in this example: 1.- are animal, age and breed variables and arguments at the same time? 2.- this refers to the class Pet, isnt? 3.- Pet is a class and at the same time an object? 4.- when we are writting: this.animal = animal, we are saying that the characteristic in this case the animal of the class Pet is equal to a new variable also called animal? 5.- why we write some times console.log and others return? for instance we write under the method speak a console.log and not a return. 6.- ernie is an object and at the same time a variable isn´t? Thanks!

Steven Parker
Steven Parker
231,275 Points
  1. animal, age and breed are parameters, which are a kind of variable
  2. the class name is Pet
  3. "Pet" is a class, and "ernie" and "vera" contain references to objects created with that class
  4. "this.animal" is the object property, and just "animal" is the parameter
  5. "console.log" puts a message on the screen, and return sends a value back to be used in the program
  6. "ernie" is a variable that contains a reference to an object