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
当前内容版权归 miguelmota 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 miguelmota .