rbi-learning / Today-I-Learned

1 stars 0 forks source link

10/20 Week 2 Day 2: JavaScript Classes #183

Open ajlee12 opened 3 years ago

ajlee12 commented 3 years ago

Classes & Methods

An older way of writing object creators and adding object methods is to use function keyword:

function createStudent(firstName, lastName) {
  return {
    region: '',
    skills: {},
    name: `${firstName} ${lastName}`,
  }
}

// To add a method:
createStudent.prototype.getName = function () {
  // ...
}

// To create an object off of createStudent:
const myObject = createStudent('Sam', 'Barli');

Classes

The class syntax is a newer and more convenient way for us to write code that creates objects.

Let the constructor take in two arguments:

class Student {
  constructor(firstName, lastName) {
    // ...
  }
}

Then use those two arguments to create a new property, name:

  constructor(firstName, lastName) {
    // The backticks treat data inside as a string unless it's between ${}, which treats data inside as JavaScript values.
    this.name = `${firstName} ${lastName}`;

    // Alternatively:
    this.name = 'firstName ' + 'lastName'; 
  }

By adding the property to the this object, we let all instances of the class have access to it.

To add methods to this class, simply add them directly inside it:

class Student {
  constructro() {
    // Some properties...
  }

  // Methods:
  getName() { /* ... */ }
  changeName(newName) { /* ... */ }
  getRegion() { /* ... */ } 
}

To create a newStudent object off this Student "mold" (i.e. the class), use the new keyword:

// newStudent object looks like: // { name: 'Samantha Barli' }


Each constructed object has access to the methods in the `class`:

```JS
const firstStudent = new createStudent('Samantha', 'Barli');
const secondStudent = new createStudent('Andy', 'Weiss');

firstStudent.getName(); // 'Samantha Sally'
secondStudent.getName(); // 'Andy Weiss'

delete Keyword

The delete keyword can be used to delete a property/value pair from an object.

Default parameters

A parameter can be initialized with default values if the function is called without passing in a value for it.

Example from MDN:

function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5, 2)); // 10

console.log(multiply(5)); // 5

How to look at all the keys in an object?


Programming tips: