Can anyone explain to me in JavaScript language what "pointers" are? -
i'm javascript coder who's learning go. i'm next tutorial: http://tour.golang.org/#52
package main import ( "fmt" "math" ) type vertex struct { x, y float64 } func (v *vertex) abs() float64 { homecoming math.sqrt(v.x*v.x + v.y*v.y) } func main() { v := &vertex{3, 4} fmt.println(v.abs()) }
i read in wikipedia , in go docs pointers are, still can understand them. can explain them me in javascript language?
they similar object references in js , other languages, not quite. pointer more powerful (and thus, more dangerous) references. consider next js code.
var = {foo: true}; var b = a; a.foo = false; console.log(b); // output: "object { foo: false }"
both a
, b
here pointer. when b = a
don't clone object, create b
refer (or point if will) same object a
. in go can both:
type t struct { foo bool } := t{foo: true} b := a.foo = false fmt.println(b) // b copy, didn't change. prints "{true}". pa := &t{foo: true} pb := pa pa.foo = false fmt.println(pb) // pb points same struct pa, prints "&{false}"
playground
the of import difference in js can't replace object within function.
var = {foo: true}; (function(x) { x = {foo: false} })(a); console.log(a); // output: "object { foo: true }"
in go can fine:
pa := &t{foo: true} func(p *t) { *p = t{foo: false} }(pa) fmt.println(pa) // output: &{false}
playground
another difference can create pointers not structs, type, including pointers.
javascript pointers go
No comments:
Post a Comment