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);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output
bar
qux
1
2
2
# 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)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Output
bar
qux
1
2
2
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22