wyc
wyc

Reputation: 55273

Can anyone explain to me in JavaScript language what "pointers" are?

I'm a JavaScript coder who's learning Go. I'm following this tutorial: http://tour.golang.org/#52

package main

import (
    "fmt"
    "math"
)

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
    v := &Vertex{3, 4}
    fmt.Println(v.Abs())
}

I read in Wikipedia and in the Go docs what pointers are, but I still can understand them. Can anyone explain them to me in JavaScript language?

Upvotes: 1

Views: 163

Answers (2)

Moshe S
Moshe S

Reputation: 1

An old question but an obvious remark is that a pointer is actually the address of the variable in memory. When passing a variable by pointer what is actually passed is the memory address where this variable is.

Upvotes: 0

Ainar-G
Ainar-G

Reputation: 36199

They are somewhat similar to object references in JS and other languages, but not quite. Pointer are more powerful (and thus, more dangerous) than references. Consider the following JS code.

var a = {foo: true};
var b = a;
a.foo = false;
console.log(b); // Output: "Object { foo: false }"

Both a and b here are like pointer. When you do b = a you don't clone an object, you make b refer (or point if you will) to the same object as a. In Go you can do both:

type T struct { Foo bool }

a := T{Foo: true}
b := a
a.Foo = false
fmt.Println(b) // b is a copy, so it didn't change. Prints "{true}".

pa := &T{Foo: true}
pb := pa
pa.Foo = false
fmt.Println(pb) // pb points to the same struct as pa, so it prints "&{false}"

Playground

The important difference is that in JS you can't actually replace the object inside a function.

var a = {foo: true};
(function(x) { x = {foo: false} })(a);
console.log(a); // Output: "Object { foo: true }"

In Go you can do it just fine:

pa := &T{Foo: true}
func(p *T) { *p = T{Foo: false} }(pa)
fmt.Println(pa) // Output: &{false}

Playground

Another difference is that you can make pointers to not just structs, but any type, including pointers.

Upvotes: 6

Related Questions