javascript中有指针吗? [英] Are there pointers in javascript?

查看:173
本文介绍了javascript中有指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前我使用过C ++,我意识到指针非常有用。 javascript中有什么东西像指针一样吗? javascript有指针吗?当我想使用类似的东西时,我喜欢使用指针:

I used C++ before and I realized that pointers were very helpful. Is there anything in javascript that acts like a pointer? Does javascript have pointers? I like to use pointers when I want to use something like:

var a = 1;
var b = "a";
document.getElementById(/* value pointed by b */).innerHTML="Pointers";

我知道这是一个非常简单的例子,我可以使用 a ,但是有几个更复杂的例子我会发现指针非常有用。有什么想法吗?

I know that this is an extremely simple example and I could just use a, but there are several more complex examples where I would find pointers very useful. Any ideas?

推荐答案

不,JS没有指针。

传递对象的副本传递对象。程序员无法访问任何代表对象地址的类似C的值。

Objects are passed around by passing a copy of a reference. The programmer cannot access any C-like "value" representing the address of an object.

在函数中,可以更改内容通过该引用传递的对象,但是您无法修改调用者具有的引用,因为您的引用只是副本:

Within a function, one may change the contents of a passed object via that reference, but you cannot modify the reference that the caller had because your reference is only a copy:

var foo = {'bar': 1};

function tryToMungeReference(obj) {
    obj = {'bar': 2};  // won't change caller's object
}

function mungeContents(obj) {
    obj.bar = 2;       // changes _contents_ of caller's object
}

tryToMungeReference(foo);
foo.bar === 1;   // true - foo still references original object

mungeContents(foo);
foo.bar === 2;  // true - object referenced by foo has been modified

这篇关于javascript中有指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆