Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
210,863 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,367 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,010 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
210,863 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