classes

classes


Examples of classes, constructors, instantiation, and “this” keyword.

Node.js

class Foo {
  constructor(value) {
    this.item = value
  }

  getItem() {
    return this.item
  }

  setItem(value) {
    this.item = value
  }
}

const foo = new Foo('bar')
console.log(foo.item)

foo.setItem('qux')

const item = foo.getItem()
console.log(item)

Output

bar
qux

Go

(closest thing to a class is to use a structure)

package main

import "fmt"

type Foo struct {
    Item string
}

func NewFoo(value string) *Foo {
    return &Foo{
        Item: value,
    }
}

func (f *Foo) GetItem() string {
    return f.Item
}

func (f *Foo) SetItem(value string) {
    f.Item = value
}

func main() {
    foo := NewFoo("bar")
    fmt.Println(foo.Item)

    foo.SetItem("qux")

    item := foo.GetItem()
    fmt.Println(item)
}

Output

bar
qux