JavaScript array of pointers like in C++ - javascript

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 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
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

"create object method pointer"
Object.defineProperty(Object.prototype,'pointer',{
value:function(arr, val){
return eval(
"this['"+arr.join("']['")+"']"+
((val!==undefined)?("="+JSON.stringify(val)):"")
);
}
});
ex of use
var o={a:1,b:{b1:2,b2:3},c:[1,2,3]}, arr=['b','b2']
o.pointer(arr) // value 3
o.pointer(['c',0], "new_value" )

Related

Possible to get a reference to the value (location) of a js object key? [duplicate]

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";
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?
No, JS doesn't have pointers.
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
You bet there are pointers in JavaScript; objects are pointers.
//this will make object1 point to the memory location that object2 is pointing at
object1 = object2;
//this will make object2 point to the memory location that object1 is pointing at
function myfunc(object2){}
myfunc(object1);
If a memory location is no longer pointed at, the data there will be lost.
Unlike in C, you can't see the actual address of the pointer nor the actual value of the pointer, you can only dereference it (get the value at the address it points to.)
I just did a bizarre thing that works out, too.
Instead of passing a pointer, pass a function that fills its argument into the target variable.
var myTarget;
class dial{
constructor(target){
this.target = target;
this.target(99);
}
}
var myDial = new dial((v)=>{myTarget = v;});
This may look a little wicked, but works just fine. In this example I created a generic dial, which can be assigned any target in form of this little function "(v)=>{target = v}". No idea how well it would do in terms of performance, but it acts beautifully.
due to the nature of JS that passes objects by value (if referenced object is changed completely) or by reference (if field of the referenced object is changed) it is not possible to completely replace a referenced object.
However, let's use what is available: replacing single fields of referenced objects. By doing that, the following function allows to achieve what you are asking for:
function replaceReferencedObj(refObj, newObj) {
let keysR = Object.keys(refObj);
let keysN = Object.keys(newObj);
for (let i = 0; i < keysR.length; i++) {
delete refObj[keysR[i]];
}
for (let i = 0; i < keysN.length; i++) {
refObj[keysN[i]] = newObj[keysN[i]];
}
}
For the example given by user3015682 you would use this function as following:
replaceReferencedObj(foo, {'bar': 2})
Assigning by reference and arrays.
let pizza = [4,4,4];
let kebab = pizza; // both variables are references to shared value
kebab.push(4);
console.log(kebab); //[4,4,4,4]
console.log(pizza); //[4,4,4,4]
Since original value isn't modified no new reference is created.
kebab = [6,6,6,6]; // value is reassigned
console.log(kebab); //[6,6,6,6]
console.log(pizza); //[4,4,4,4]
When the compound value in a variable is reassigned, a new reference is created.
Technically JS doesn't have pointers, but I discovered a way to imitate their behavior ;)
var car = {
make: 'Tesla',
nav: {
lat: undefined,
lng: undefined
}
};
var coords: {
center: {
get lat() { return car.nav.lat; }, // pointer LOL
get lng() { return car.nav.lng; } // pointer LOL
}
};
car.nav.lat = 555;
car.nav.lng = 777;
console.log('*** coords: ', coords.center.lat); // 555
console.log('*** coords: ', coords.center.lng); // 777

Modifying variables that are passed by reference in Javascript

I was watching a JavaScript talk, and the tutor said that if we pass a property of an object in a function it will actually change the real value, because we will be passing the variable by reference. Here is the slide:
but when I tried to practice the concept, that wasn't the case. Here is my code:
var obj = {val: 5};
function changeVal(x) {
x = x+5;
return x;
}
console.log(obj.val) // 5
console.log(changeVal(obj.val)) // 10
console.log(obj.val) // 5
I was expecting obj.val to change to 10.
Please tell me what's wrong here, and correct me if I am wrong. Thanks
You are passing not the object, but the primitive type. So when you pass the val of the obj, it is a number and is a primitive type.It copies the val and passes the copy to the object.
If you pass like this, it will work
var obj = {val: 5};
function changeVal( param ) {
param.val = param.val + 5;
return param.val ;
}
console.log(obj.val) // 5
console.log(changeVal(obj)) // 10
console.log(obj.val) // 10
You are not actually passing an object, just passing the value of property(val).
If you will pass obj in changeVal(), then it will actually change the value of the property of passed object.
For that you need to do like:
var obj = {val: 5};
function changeVal(x)
{
x = x+5;
return x;
}
console.log(obj.val); // 5
changeVal(obj); // Need to pass object instead of value of the property's value
console.log(obj.val); // 10
Primitive types (string, integer, boolean, etc...) are immutable, which means if you change one of the values inside a function, the callee (scope which calls your function) will not see the change.
function doSomething(a) {
a = a + 1;
}
var value = 2;
console.log(value); // result: 2
doSomething(value);
console.log(value); // result: 2
Pass-by-reference only works for objects. Like this:
function doSomething(obj) {
obj.attribute = obj.attribute + 1;
}
var myObject = {attribute: 2};
console.log(myObject.attribute); // result: 2
doSomething(myObject);
console.log(myObject.attribute); // result: 3
More reading about Javascript types:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
Say for instance you have an Iphone . Now lets say a manufacturing company calls you and asks to borrow your Iphone for a reference just so they can design an Iphone that is similar and sell it to customers . Your original Iphone still exists and is never gone , but every now and then the factory needs to use it for a reference , think of your function as the factory that just make a copy of obj.
//Original data
var obj = {val: 5};
Once your function returns something , it technically becomes a value
Example :
return 3; is a value of 3
so
function changeVal(x) {
x = x+5;
return x;
}
is a new value of x which in this case would be x + 5;
x is a copy of whatever you pass into the function .
Hope this helps.

Getting a reference to an array element

While I realize that an array, as a non-primitive data type, is handled by references in JavaScript, not by value, any particular element of that array could be a primitive data type, and I assume then that it is not assigned by reference.
I'd like to know how to get a reference to an individual element in an array so that I don't have to keep referring to the array and the index number while changing that element?
i.e.
var myElement=someArray[4]
myElement=5
//now someArray[4]=5
Am I misinterpreting various docs that imply but do not explicitly state that this is not the intended behavior?
You can make a copy of an array element, but you can't create a value that serves as an alias for an array property reference. That's also true for object properties; of course, array element references are object property references.
The closest you could get would be to create an object with a setter that used code to update your array. That would look something like:
var someArray = [ ... whatever ... ];
var obj = {
set element5(value) {
someArray[5] = value;
}
};
Then:
obj.element5 = 20;
would update someArray[5]. That is clearly not really an improvement over someArray[5] = 20.
edit — Now, note that if your array element is an object, then making a copy of the element means making a copy of the reference to the object. Thus:
var someArray = [ { foo: "hello world" } ];
var ref = someArray[0];
Then:
ref.foo = "Goodbye, cruel world!";
will update the "foo" property of the object referenced by someArray[0].
You can always pass around a closure to update this:
var myUpdater = function(x) {
someArray[4] = x;
}
myUpdater(5);
If you want read/write capabilities, box it:
var makeBox = function(arr, n) {
return {
read: function() { return arr[n]; },
write: function(x) { arr[n] = x; }
};
}
// and then:
var ptr = makeBox(someArray, 4);
ptr.read(); // original
ptr.write(newValue);
someArray[4]; // newValue

How did the value of Object Array in javascript be operated?

I feel puzzled when I rethink of these two functions:
The first one goes like this:
var test = [1,2,3];
var ele = test[0];
ele= 2;
alert(test[0]);
The result is 1. I think this is obvious. But when I meet this:
var test = [{id:1},{},{}];
var ele = test[0];
ele.id = 2;
alert(test[0].id);
The result turns to be 2
So could anyone tell me that how the javascript work when it happens like this in the object array?
In JavaScript, objects are assigned by reference, rather than copied in memory. So if you assign an existing object to a different variable, both will point to the same object in memory. Modifications to either will therefore be reflected in both.
var a = {id: 1, name: "bob"};
var b = a;
console.log(b.name); // bob
b.name = "bill";
console.log(a.name); // bill
So in your example, executing ele.id = 2; operates on the memory location holding the object at test[0]. The change to the id property of that object is reflected in both variables referencing it (test[0], ele)
Note that if you had assigned the entire array test to ele, modifying one of the array members would have been reflected in both test, ele since Arrays are objects in Javascript:
var test = [1,2,3];
// Assign array test to ele
var ele = test;
// Modify one member
ele[0] = 2;
alert(test[0]); // 2

Javascript: Behavior of {}

I didn't have a understanding on
difference between intializing a
variable with {} and a named-function
with new keyword. I mean which
practice should I use to give a
definition of an object. Which is more
appropiate and for which case?
Then I made a little example to test
both practices. And
I found a very simple difference.
Whenever you intialized an
variable with {}, that variable is
the only reference of this object
definition given in {}. {} itself
doesn't have a name so it can't be
called to intialized with new. Only a
reference is avaliable to get it.
So it seems we can easily implement
singleton pattern on objects using {}.
What I see you can't have more than
one instances with {} not even you can
apply clone if you do you will get
only a reference of that object.
Am I assuming a correct behavior of
{}?
var A = {
B : 0
};
// A is an object?
document.write("A is an " + typeof A);
Lets try to clone object A
var objectOfA = new Object(A);
objectOfA.B = 1;
//Such operation is not allowed!
//var objectOfA = new A();
var referenceOfA = A;
referenceOfA.B = -1;
document.write("A.B: " + A.B);
document.write("<br/>");
The above referenceOfA.B holds a reference of object A, so changing the value of referenceOfA.B surely reflects in A.B.
document.write("referenceOfA.B: " + referenceOfA.B);
document.write("<br/>");
If successfully cloned then objectOfA should hold value 1
document.write("objectOfA.B: " + objectOfA.B);
document.write("<br/>");
Here are the results:
A is an object
A.B: -1
referenceOfA.B: -1
objectOfA.B: -1
This may be of use, excerpt:
CatNames.instance = null; // Will contain the one and only instance of the class
// This function ensures that I always use the same instance of the object
CatNames.getInstance = function() {
if (CatNames.instance == null) {
CatNames.instance = new CatNames();
}
return CatNames.instance;
}
Note: you should not clone singletons.
A is already an object, so new Object(A) just returns A. You can prove this by running
var c = {};
alert(c === new Object(c));
So no cloning is going on.
What are you actually trying to do, and what does the Singleton pattern have to do with this cloning business?
For cloning objects you will have to do a bit more work. Something like below.
var a = {
val:1,
clone : function(){
return {val: a.val, clone : a.clone}
}
};
var b = a.clone();
b.val = 2;
console.log(a);
console.log(b);
Now you can clone an object and change it values. If you want to clone more complex objects, you could write a recursive function for this.
You can use these object literals as either static classes or as objects with key/value pairs.
If you want to use non static classes (sort of), use the following:
var MyClass = new function(){}
MyClass.prototype = {
val : 1
};
var a = new MyClass();
Hope this helps.

Categories

Resources