loading...

Intro to JavaScript Classes

jasterix profile image Jasterix ・3 min read

Classes are used to create objects:

  • class <––– object

Vocabulary

  • instance properties => what they have instance methods => what they do
  • constructor => method that is run once when the object is bring created -- used to set up your object
  • this keyword => refers to the object created by the class (the instance)

Creating a class:

class Rectangle {
  constructor (_width, _height) {
    console.log("Creating a rectangle")
    this.width = _width (instance property)
    this.height = _height (instance property)
 ,, }
  getArea () (instance method) {
     return this.width * this.height
    }

  printDescription() (instance method) {
    console.log(`I am rectangle a of ${this.width} x ${this.height}
   }
}
Try it out:
let myRectangle1 = new Rectangle(2, 6)
let myRectangle2 = new Rectangle(10, 6)

console.log(myRectangle1.getArea())
myRectangle2.printDescription()


Getters and Setters

Getter

  • Used to define methods on a class, which are then used as if they are properties

Setter

  • Assign new values to instance properties
class Square {
  constructor (_width) {
    this.width =_width
    this.height = _width
    }

  get area() {
    return this.width * this.height
  }

  set area(area) {
    this.width = Math.sqrt(area)
    this.height = this.width
  }
}
Try it out:
let square1 = new Square(4)
console.log(square1.area)
square1.area = 25 //modifies the value of square sides to 5
console.log(sqare1.width)

Static Method

  • Method you can define on a class but that does not require an instance of the class to be created in order to be used
  • Static method is called on the square class itself. Also called a helper method
  • Does not have an object bound to them
  • Does not use the this keyword
class Square {
  constructor (_width) {
    this.width = _width
    this.height = _height
  }

  static equals (a, b) {
    return a.width * a.height === b.width * b.height
  }

  static isValidDemensions (width, height) {
    return width === height
  }
}
Try it out:
let square1 = new Square(8)
let square2 = new Square(9)

console.log(square1, square2)
console.log(Square.isValidDimensions(7,6))

Inheritance with extend

  • Uses the extend keyword
  • Parent class is used to create new child class
  • The child class takes attributes and behavior of the parent. It will also have its own custom behavior
class Person {
  constructor (_name, _age) {
    this.name = _name
    this.age = _age
  }

  describe() {
    console.log(`I am ${this.name} and I am $this.age} years old.`

  }
}

class Programmer extends Person { //child class Programmer of Person
  constructor (_name, _age, _yearsOfExperience) {
    super(_name, _age) //calls the properties from the parent class)

    //custom behavior
    this.yearsOfExperience = _yearsOfExperience
  }

  code () {
    console.log(`${this.name} is coding`)
  }

Try it out:

let p1 = new Person("Sheva", 45)
let programmer1 = new Programmer("Ayana", 56, 12)

const programmers = [
new Programmer("Frank", 62, 5),
new Programmer("Jane", 25, 4
];

function developSoftware (programmers) {
  for (let programmer of programmers) {
    programmer.code()
  }
}

Polymorphism

  • Act of redefining a method inside a derived child class of a parent class
  • When you override a method with the one in the child class, instead of using what's in the parent class
class Animal {
  constructor(name){
    this.name = name
  }
  makeSound () {
    console.log("Generic sounds")
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name)
  }
  makeSound() {
    super.makeSound() //calls the parent class first, then child class
    console.log("Woof!")
  }
}
const a1 = new Animal("Dom")
a1.makeSound()

const a2 = new Dog("Jeff")
a2.makeSound()

HTML List Binding

  • Creating a class that can manipulate the DOM directly
<ul id = "myList">
//<-----JavaScript List will go here----->
</ul>

<script src = "ListBinding.js"> </script>

<script type = "text/javascript">
const myList = document.getElementById("myList");
const listBinding = new ListBinding(myList);
</script>
ListBinding.js
class ListBinding {
  constructor (element) {
    this.listElement = element;
    this.textList = ["abc", "is as easy","as 123" ]
  }

  //Makes an <li>text</li> element/tag

  static createListItem (text) {
  const li = document.createElement("li");
    li.textContent = text;
    return li;

  update() {
  // 1---- remove all existing <li> tags
    while (this.listElement.firstChild) {
      this.listElement.removeChild(this.listElement.firstChild)
    }

  // 2---- Fill <ul> tag with <li>
    for (const text of this.textList) {
      this.listElement.appendChild(ListBinding.createListItem(text))
    }
  }
}

  add (text) {
    this.textList.push(text)
    this.update()
  }

  remove (index) {
    this.textList.splice(index, 1);
    this.update();
  }
}

Freecodecamp.org Video tutorial I used:

https://youtu.be/2ZphE5HcQPQ

Posted on by:

jasterix profile

Jasterix

@jasterix

Passionate about building great technology and connecting with people to create positive change. Find me elsewhere @jasterix or @_jasterix

Discussion

pic
Editor guide