dongxianshuai8927 2014-10-18 06:50
浏览 68
已采纳

谁能用JavaScript语言向我解释什么是“指针”?

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?

  • 写回答

2条回答 默认 最新

  • dongmu7335 2014-10-18 07:18
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看