Reputation: 52957
var obj = {a:1,b:2};
function parent_object(num){
console.log('This number is inside the object ',<????>);
}
parent_object(obj.a)
This should output pointing to obj. The only way I found to do this is boxing every number object in an object which would keep a reference to the parent. This is, though, a performance killer. Is there a better way of keeping track of the location of a number?
Upvotes: 2
Views: 385
Reputation: 4118
Actually no. And not only in JavaScript, but in none of the other conventional languages.
As far as I know, the only way would be for you to do exactly what you yourself said: boxing the number (or any other field type) in an object that would keep a reference (maybe by constructor injection) to its enclosing parent.
The boxing in question can be thus accomplished:
BoxedValue = function(value, parent) {
this.value = value;
this.parent = parent;
}
var i = {};
n.i = new BoxedValue(12, i)
console.log(i.n.parent);
However, generally speaking, the most important factor in your JavaScript application's performance for current browsers is the way you handle your memory usage. Therefore, this approach isn't really advisable, and I suggest you solve your problem, whatever it might be, via some other method.
Upvotes: 3
Reputation: 2278
var obj = {a:1,b:'string',c:2}
for(prop in obj){
if(typeof obj[prop]=='number'){
console.log(prop + ' : ' + obj[prop] + ' found')
}
}
logs:
a : 1 found
c : 2 found
Upvotes: 0
Reputation: 46183
There is no way to do this, because you can have objects reference each other from multiple places:
var num = 1;
var obj = {a: num, b: 2};
var obj2 = {x: num};
parent_object(obj.a); // should it return obj or obj2? Both are technically correct!
What are you really trying to solve here? There is probably a better approach available to you.
Upvotes: 0