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

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

Related

What exactly is the `in` keyword in JavaScript? [duplicate]

This question already has answers here:
What does the 'in' keyword in javascript mean?
(3 answers)
Closed 1 year ago.
Ok so I have seen the in keyword in many different codes but i have never understood what they do.
Here is an example
let duck = new Bird() // Bird is a constructor i made. Not important
function in keyword() {
let ownProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
}
}
}
Sooo, what does it do?
Please explain it to me
The in operator tests if the string on the left side of the operator is a property name in the object on the right side.
let obj = { a: 1 };
console.log("a" in obj); // true
console.log("b" in obj); // false
The in keyword also plays a role in the for ... in loop, which iterates through the properties (the enumerable properties) of an object:
let obj = { a: 1, b: 2 };
for (let x in obj) {
console.log(x);
}
That will log "a" and "b", because those are the enumerable properties of the object.

Overriding function named params in Javascript? [duplicate]

This question already has answers here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
ES6 Object Destructuring Default Parameters
(1 answer)
Closed 2 years ago.
function lookupRecord2({value1 = "blue", value2 = 7}) {
console.log('theValues');
console.log(value1);
console.log(value2);
}
lookupRecord2( { value1: 'pink', value2: 9 } );
I've read that Javascript doesn't allow for named parameters so I'm confused how the above code works. What is happening here that's allowing me to override the params?
I think what's confusing is that the params are assigned with "=" whereas the object I'm passing uses ":" ...
ADDED:
I know this is a form of destructuring, but I still can't make sense of it b/c it's in the function declaration.
function des({ a = 1, b = 2 } = {}) {
console.log(a);
console.log(b);
}
des();
This is a destructing syntax where we're able to pass default values.
It works everywhere, not just in function declarations.
{ a = 1, b = 2 } = { b:3 }
// assigns 1 to "a" and because "b" already exists, "b" is 3
MORE INFO HERE: can someone explain this seemingly weird assignment `{key=value} = argument`

Using a string to call an object [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
I am trying to create a program that defines the variable finalResult based on variable input. The input variable should call on an object inside of object A:
var input = "";
var A = {
AA: {
result: 0
},
AB: {
result: 1
}
}
var finalResult = A.input.result;
So if input = "AA", then the final result should be 0, but if input = "AB", then the final result should be 1.
You can do A[input].result, which assumes the value of input is present as a property in A. If the property isn’t present you’ll get an error trying to access result on undefined. You can guard against this by OR’ing it with an empty object:
(A[input] || {}).result // undefined if A[input] isn’t present

Why does a const constant assign an object, and a constant can modify the value of the object? [duplicate]

This question already has answers here:
Why can I change a constant object in javascript
(12 answers)
Closed 4 years ago.
enter image description here
Why myVariable can be modified?
const obj = {
a: 'a'
}
const myVariable = obj;
try{
myVariable = { a: 'c' } //The const declaration creates a read-only reference to a value
}catch(e){
console.log(e);
}
myVariable.a = 'b';
console.log(myVariable); //{a: "b"}
This happens because your constant is actually storing a reference to the object. When you're adding to object you're not re-assigning or re-declaring the constant,you're just adding to the "list" that the constant points to.Refer more here : Why can I change value of a constant in javascript

Accessing parent object in javascript [duplicate]

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

Categories