Accessing parent object in javascript [duplicate] - javascript

This question already has answers here:
Access parent's parent from javascript object
(12 answers)
Closed 8 years ago.
I have the following code in javascript :
var x = {
a:1,
b : {
c : 2,
d : //i want value of x.a in here
}
}
I have read that accessing parent property like this is not at all possible. Is there any workaround for this?

No, there isn't. Nested objects don't have access to their hosts as in any other language as well.
You have to set the explicitly by yourself.

No, it's not possible, but your case can be written like:
var x = new function(){
this.a = 1;
this.b = {
c: 2,
d: this.a
}
};

A javascript object doesn't have a parent because you can have sharing. For example:
var a = { x: 42 };
var b = { y: a };
var c = { z: a };
here the object a is "shared" as sub-object between b and c, so what should be the "parent" or a? You can see the sharing because after executing b.y.x = 99, also c.z.x will show be 99. A single javascript object may be reachable using different paths.
DOM objects on the other hand have a parent because the DOM is a tree structure and it makes sense to talk about "the" parent of a node.
If you add a DOM node as a child of another and the node is already part of the DOM it will be removed from where it is and it will be placed in the new position.

The parent reference does not exist in javascript. What you can do is build an helper recursive function that will parse all your object and add a reference to the parent. This will build a more complex object.
Here is a video which shows how to : http://blog.wax-o.com/2014/01/how-to-find-deep-and-get-parent-in-javascript-nested-objects-with-recursive-functions-and-the-reference-concept-level-beginner/

try this:
var x = {
a: {
c: 1
},
b: {
c: 2
}
}
x['b']['d'] = x['a'];
should work ;)

Related

How to get the same behavior in an object when the value is copied to another variable

In this console:
When B is set to A but A was destroyed afterwards, B.b() throws an error because A is truly undefined.
How can one avoid this?
PS: I am aware that I can simply return this (or change the function in some way) but that doesn't fulfill my purposes.
EDIT: How do I 'localise' and somehow tell javascript that by A, I mean B even if A is undefined, WITHOUT ALTERING THE FUNCTION ITSELF?
You should change your A to look like the following:
let A = {
a: "a",
b: function() {
// change A.a to this.a
return this.a;
}
};
Right now since it references A when you destroy A Even though B is already equal to A the b method still needs the original A to exist. Swapping it for this will fix the issue.
The way the question and example is written that "error" cannot be avoided. return A.a; will and SHOULD be undefined based on your example because you are assigning A = undefined;
Also, if you are trying to clone an object, there are a couple of other options you should look into like:
let B = JSON.parse(JSON.stringify(A));
let B = Object.assign({}, A); MDN
Javascript classes
And maybe check out this answer: How do I correctly clone a JavaScript object?
To the new viewers, if you want to do this without altering the function:
var A = (function() {
var A = {a: 90, b: function() { return A.a }}; // same object as in the Q
return A;
})()
console.log(A.b()) // 90
var B = A;
A = undefined;
console.log(B.b()) // Also 90
B.a = 89;
console.log(B.b()) // 89

prototypical inheritance in javascript ,cloning property [duplicate]

This question already has answers here:
Setting a variable equal to another variable [duplicate]
(3 answers)
Closed 3 years ago.
how can I achieve below things in javascript
var parent = {
a: 5,
b: 6
}
var child = parent;
console.log(child.b); // 6
//now if I change the value of b
parent.b = 7
console.log(parent.b); //7
console.log(child.b); //7
//but I want to preserve the previous value of the object property it should not change now.it should show 6 instead of 7 in case of console.log(child.b)
https://codebunk.com/b/696347863/
When you do var child = parent both child and parent refer to the same object instance in memory. If you want to copy the property of parent to the child you need to create a new object with the same keys as the parent object.
You can use spread ... or object.assign for this
var parent = {
a: 5,
b: 6
}
var child = {...parent};
var child1 = Object.assign({}, parent);
console.log(child.b); // 6
console.log(child1.b); // 6
//now if I change the value of b
parent.b = 7
console.log(parent.b); //7
console.log(child.b); //6
console.log(child1.b); //6
For deep cloning, we need to use other alternatives because Object.assign() and ... copies property values. If the source value is a reference to an object, it only copies that reference value.

Object literal constructor

I am looking for a way to modify an object that was defined by a literal without passing it into another function.
example:
let o = {a:1,b:2}
console.log(o.a===3)
i thought when i define an object using a literal the the Object constructor would be called, so i did override Object.prototype.constructor but it only gets called when i do new Object({a:1,b:2})
question in simpler terms can anyone make a=3 without passing the object o to a function or a proxy or using o.a=3 or with keyword, where o is defined using an object literal?
Just do o.a=3; and console log o:
let o = {a:1,b:2};
o.a=3;
console.log(o);
Currently you are doing o.a===3 which will return Boolean value instead of overwriting the value of property a.
You also cannot do o.a=3 inside console.log() because o.a=3 will return the assigned value which is 3 but it will still change the property a of o to 3.
let o = {
a: 1,
b: 2
};
//won't print o but changes o.a to 3
console.log(o.a = 3);
It's simply not possible.
There is no constructor of an object literal.
You can create objects in different ways:
via an object literal or
via a constructor function or
via Object.create
Also, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
question in simpler terms can anyone make a=3 without passing the object o to a function or a proxy?
o.a = 3;
I am looking for a way to modify an object that was defined by a literal without passing it into another function.
Thats impossible, cause if it would be possible you could break every piece of javascript. And that would be terrible.
Oh wait, this is JS...
with({ get o() { return { a: 3 }; }, set o(v) {} }) {
o = {a:1,b:2};
console.log(o.a===3) // true
}
What you want to achieve could be done if o.a holds a reference to the variable a - which unfortunately only works the way you'd like for variables that are passed by reference. Primitive types like String, Number and Boolean though, are passed by value.
Check the examples below:
var a = 1;
var o = { a: a };
a = 2;
console.log(o.a, a);
It also doesn't help to use an Object constructor like new Number() because that does return a reference to an object (which is passed by reference as you'd need), but assigning a new value to it reading the value still returns a primitive (which is, again, passed by value):
var a = new Number(1);
var o = { a: a.valueOf() };
a = Number(2);
console.log(o.a, a);
If you pass something that is naturally passed by reference, your expectation is fulfilled:
var a = [ 1 ]
var o = { a: a }
a[0] = 2
console.log(o.a[0])

What does it mean to add a prototype to a function? [duplicate]

This question already has answers here:
How does JavaScript .prototype work?
(26 answers)
Closed 8 years ago.
Given:
var x = function () {
};
x.prototype = { abc: 25 };
Can someone explain to me what this means. Could this be done all inside a function without the .prototype?
var x = function () {
// something here ?
};
Prototypes are how the class model works in JavaScript - you've created a class x that has a property abc which defaults to 25:
var obj = new x();
alert(obj.abc); // 25
The function x is the class constructor, it is called when a new instance of that class is created and can initialize it. And that means of course that you can just set the abc property there:
var x = function()
{
this.abc = 25;
};
var obj = new x();
alert(obj.abc); // 25
This is supposedly the less efficient approach however:
You have to manipulate each object created rather than setting the property on the prototype once and forever.
The property is stored on each object and consumes memory each time, as opposed to being stored once on the prototype.
ECMAScript Harmony has a nicer syntax for defining classes and prototypes, however this one isn't implemented in any browser yet:
class x {
constructor() {
...
}
public abc = 25;
}
This is equivalent to your code defining the prototype, merely grouping related operations a little better.

Access attributes inside of object while in object in JavaScript [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 8 years ago.
I'm having a bit of an inception issue right now. I'm trying to reference an attribute of an object while creating another attribute of the object.
For example:
var x = {
a1 : "a",
b2 : this.a1,
c : "c"
}
alert(x.a1); // Returns properly
alert(x.b2); // Returns undefined.
If I try to make b2 reference x.b2, it doesn't work either. Can anyone point me in the right direction?
All in all, I'm trying to decide the value of b2 based on the value of a1 without having to take another step out of the object.
Here's a fiddle -- http://jsfiddle.net/fpG9h/
You are most definitely in need of getters and setters. You can define them like this
var obj = {
a1: "a",
get b2() {
return this.a1;
},
set b2(value) {
this.a1 = value;
},
c: "c"
}
console.log(obj.b2); // a
obj.b2 = "bbb";
console.log(obj.b2); // bbb
console.log(obj.a1); // bbb

Categories