classes


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

Node.js

  1. class Foo {
  2. constructor(value) {
  3. this.item = value
  4. }
  5. getItem() {
  6. return this.item
  7. }
  8. setItem(value) {
  9. this.item = value
  10. }
  11. }
  12. const foo = new Foo('bar')
  13. console.log(foo.item)
  14. foo.setItem('qux')
  15. const item = foo.getItem()
  16. console.log(item)

Output

  1. bar
  2. qux

Go

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

  1. package main
  2. import "fmt"
  3. type Foo struct {
  4. Item string
  5. }
  6. func NewFoo(value string) *Foo {
  7. return &Foo{
  8. Item: value,
  9. }
  10. }
  11. func (f *Foo) GetItem() string {
  12. return f.Item
  13. }
  14. func (f *Foo) SetItem(value string) {
  15. f.Item = value
  16. }
  17. func main() {
  18. foo := NewFoo("bar")
  19. fmt.Println(foo.Item)
  20. foo.SetItem("qux")
  21. item := foo.GetItem()
  22. fmt.Println(item)
  23. }

Output

  1. bar
  2. qux