指针的JavaScript数组就像在C ++ [英] JavaScript array of pointers like in C++

查看:119
本文介绍了指针的JavaScript数组就像在C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面对在JavaScript中的情况时,我需要通过它的指针类似С++指针数组对象的搜索结果更新对象
例如code代表我的问题:

I'm faced with a situation in JavaScript when I need to update an object via its pointer similar to С++ array of pointers to objects

Example code for my issue:

var foo = new Array();
var bar = function(){ 
    this.test = 1;
    foo.push(this); // push an object (or a copy of object?) but not pointer
};
var barInst = new bar(); // create new instance
// foo[0].test equals 1
barInst.test = 2;
// now barInst.test equals 2 but
// foo[0].test still equals 1 but 2 is needed

所以,我怎么能解决这个问题?我应该用一个回调或类似这样的东西,或有一个简单的方法来帮助我避免复制对象,而不是推原始指针到一个数组?

So, how can I solve this? Should I use a callback or something like this or there is an easy way to help me to avoid copying the object instead pushing the raw pointer into an array?

推荐答案

JS是通过按值,所以原来的任务是 this.test =值1 ,在我的例子,这是 this.test =对象由ptr 指出,所以当我改变 PTR this.test 也会改变。

JS is pass-by-value, so your original assignment was this.test = the value of 1, in my example, it's this.test = the object pointed to by ptr, so when I change ptr this.test changes as well.

var foo = [],
    ptr = {val: 1},
    bar = function(){ 
       this.test = ptr;
       foo.push(this); // push an object (or a copy of object?) but not pointer
    },
    barInst = new bar(); // create new instance
    // foo[0].test.val equals 1
    ptr.val = 2;
    // foo[0].test.val equals 2

但如果你认为 foo.push(本); 相似,其实不然。由于这是一个对象,数组的确会含有原始指针的对象,就像你想要的。你能证明这只是:

Although if you thought that foo.push(this); was similar, it isn't. Since this is an object, the array will indeed contain "raw pointers" to objects, just like you want. You can prove this simply:

foo[0].test = 3;
// barInst.test === 3

由此说明,这的确是一个指向对象被压入阵列

Which shows that it is indeed a pointer to the object that was pushed onto the array

这篇关于指针的JavaScript数组就像在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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