Access previous values within object during declaration [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Self-references in object literal declarations
var obj = {
value: 10,
value2: value + 2
};
How can I do the above? (Assuming it's even possible)
I am using a lot of jQuery's $.extend to add more properties that rely on the previous values being added; so that modifying a few values automatically correct the rest.

You can't do it in declaration, but you could always make a function. The following will always return a value 2 greater than that stored in value:
var obj = {
value: 10,
getValue2: function(){ return this.value + 2; }
};
If you don't want the value of value2 to change along with value, you could declare a placeholder variable and declare the object using that:
var placeholder = 10;
var obj = {
value: placeholder,
value2: placeholder + 2
};

I am not 100% sure if you can do this at the time of declaration. You could, however, do it afterwards:
using extend:
var obj = {
value: 10
};
$.extend(obj, {
value2: obj.value + 2
});
http://jsfiddle.net/KgKgf/
just javascript:
var obj = {
value: 10
};
obj.value2 = obj.value + 2;
http://jsfiddle.net/KgKgf/1/

Related

JSON Definitions Using Internally Defined Variables [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 5 years ago.
I am trying to create a JSON object to store some parameters for a program. Some of the parameters need to be calculated from others as they are being defined. I would like to do this within the object definition but maybe this is not possible
var params = {
a: 50,
b: 70,
c: this.a+this.b
}
Result
What happens
>params.c
NaN
What I wished happened
>params.c
120
Edit
After doing some further reading, I think I am using Object Literal Notation instead of JSON.
You can use this approach:
To avoid re-calculation, use the function Object.assign.
The get syntax binds an object property to a function that will be called when that property is looked up.
var params = {
a: 50,
b: 70,
get c() {
console.log('Called!');
return this.a + this.b;
}
};
console.log(params.c); // Prints 120 then Called!
console.log(params.c); // Prints 120 then Called!
var params = Object.assign({}, {
a: 50,
b: 70,
get c() {
console.log('Called from function Object.assign!');
return this.a + this.b;
}
});
params.a = 1000; // To illustrate.
console.log(params.c); // Prints 120
console.log(params.c); // Prints 120
.as-console-wrapper {
max-height: 100% !important
}
Resources
Object initializer
getter
Personally, I would create constants (since magic numbers are the devil), but this is an overly-simplistic example:
const FIFTY = 50;
const SEVENTY = 70;
var params = {
a: FIFTY,
b: SEVENTY,
c: FIFTY + SEVENTY
};
What I would recommend doing is starting with an object that does not contain c, and taking the calculation outside of the object. Once the calculation has occurred, simply add the sum back to the object as a new key/value pair:
var params = {
a: 50,
b: 70,
}
var sum = 0;
for (var el in params) {
if (params.hasOwnProperty(el)) {
sum += params[el];
}
}
params['c'] = sum;
console.log(params);

Destructuring declaration bug with the value

I can not understand why after destructuring assignment, items prop does not equal Gorilla.
It will be used after deleting the main prop items: "Piggi" in the origin object options. I do not understand why...
'use strict';
let options = {
size: 100,
items: "Piggi"
}
let { title="Menu", items:w="Gorilla", size } = options;
let a = title;
let b = w;
console.log(a + " - " + b); // must be "Menu - Gorilla"
In the destructuring declaration with initialization here:
let { items:w = "Gorilla" } = options;
the syntax means to declare a variable called "w", whose value should be initialized to the value of the property called "items" in the object referenced by "options", or if there is no such property then to the string "Gorilla".
In your case, then, the variable "w" is initialized to the value of the "items" property in the original object.
If you don't want to take the value from the source object, then don't:
let w = "Gorilla";
When you analyze the code, you get three techniques working here:
short hand properties
{ foo, bar }
for
{ foo: foo, bar: bar}
default values
{ foo = 42 }
which is
{ foo: foo = 42 }
change of the target in the Object Property Assignment Pattern [You Don't Know JS: ES6 & Beyond, Chapter 2: Syntax]:
The syntactic pattern here is source: target (or value: variable-alias).
{ foo: bar }
The synthesis is a new target w for the old property items with a default value of 'Gorilla'.
let options = {
size: 100,
items: "Piggi"
}
let { title="Menu", items:w="Gorilla", size } = options;
let a = title;
let b = w;
console.log(a + " - " + b);
Solution- The problem is , we are overwriting the global object. it is why you have titile as Menu but option object does not have titile property. So, when you assign global object with option,
it still has items as "piggi"
plus you cannot assign object like this, you have to reassign each property in javascript.
i hope you got your answer.

Use object values as new values inside same object [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 8 years ago.
I am trying to do something like this:
var obj = {
a: 5,
b: this.a + 1
}
(instead of 5 there is a function which I don't want to execute twice that returns a number)
I can rewrite it to assign obj.b later from obj.a, but can I do it right away during declaration?
No. this in JavaScript does not work like you think it does. this in this case refers to the global object.
There are only 3 cases in which the value this gets set:
The Function Case
foo();
Here this will refer to the global object.
The Method Case
test.foo();
In this example this will refer to test.
The Constructor Case
new foo();
A function call that's preceded by the new keyword acts as a constructor. Inside the function this will refer to a newly
created Object.
Everywhere else, this refers to the global object.
There are several ways to accomplish this; this is what I would use:
function Obj() {
this.a = 5;
this.b = this.a + 1;
// return this; // commented out because this happens automatically
}
var o = new Obj();
o.b; // === 6
This should return the correct values:
function () {
var aVar = 5;
var bVar = aVar + 1;
return {
a : aVar,
b : bVar;
}
}();
As it turns out you can't reference an object inside another object unless the first one is a function. But you can do it this way.
var obj = {
a: 5
}
obj.b = obj.a + 1; // create field b in runtime and assign it's value
If you console.log(obj) you will have
obj = {
a: 5,
b: 6
}
This way you keep the object literal structure for the remaining part of the code
No, in your example, the value of this doesn't refer to the object literal.
You'll need to assign a value to b after the object has been created in order to base it on another property in obj.
in chrome debugger
> var o = {a: 5, b: this.a+1}
undefined
> o.b
NaN
> o.a
5
No. this will take the same meaning as it would outside the definition.

JavaScript How to delete key from copied object? [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 7 years ago.
I have query object
var q = {
age: 10,
'profile.contry': 'india'
};
Now I duplicate the q variable and remove key from a duplicate variable.
var duplicateQ = q;
delete duplicateQ['profile.contry']; // I have removed 'profile.country' from duplicateQ.
console.log(q); //Object { age: 10 }
console.log(duplicateQ); //Object { age: 10 }
Why are both the variables affected? How can I remove the property from only one of them?
It's because q and duplicateQ refer to the same object. Thus, when you delete a property on one object, it effects both (since they both point to the same object).
You need to copy/clone the object.
In ES6, you can use the .assign() method:
var q = {age:10, 'profile.contry': 'india'};
var duplicateQ = Object.assign({}, q);
delete duplicateQ['profile.contry'];
Output:
console.log(q);
// {age: 10, profile.contry: "india"}
console.log(duplicateQ);
// Object {age: 10}
You aren't duplicating q, instead, you're copying a reference to different variable.
Both q and duplicateQ point to the same object, the same location in your computer's memory.
In order to make this work, you're going to have to clone the object, then you can delete (/ modify) individual properties on the separate variables.
A quick-and-dirty example:
var a = { a: 1, b: 2 },
b = JSON.parse(JSON.stringify(a));
delete b.a;
document.body.textContent = JSON.stringify(a) + ' ' + JSON.stringify(b);

Print / display a JavaScript variable's name instead of it's value

Is it possible to print / display a JavaScript variable's name? For example:
var foo=5;
var bar=6;
var foobar=foo+bar;
document.write(foo+ "<br>");
document.write(bar+ "<br>");
document.write(foobar + "<br>");
How would we print the variable's names so the output would be:
foo
bar
foobar
Rather than:
5
6
11
You can put the variables in an object then easily print them this way: http://jsfiddle.net/5MVde/7/
See fiddle for everything, this is the JavaScript...
var x = {
foo: 5,
bar: 6,
foobar: function (){
var that=this;
return that.foo+that.bar
}
};
var myDiv = document.getElementById("results");
myDiv.innerHTML='Variable Names...';
for(var variable in x)
{
//alert(variable);
myDiv.innerHTML+='<br>'+variable;
}
myDiv.innerHTML+='<br><br>And their values...';
myDiv.innerHTML+='<br>'+x.foo+'<br>'+x.bar+'<br>'+x.foobar();
The JavaScript for...in statement loops through the properties of an object.
Another variation (thanks #elclanrs) if you don't want foobar to be a function: http://jsfiddle.net/fQ5hE/2/
Utils = {
eventRegister_globalVariable : function(variableName,handlers){
eventRegister_JsonVariable(this,variableName,handlers);
},
eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
if(jsonObj.eventRegisteredVariable === undefined) {
jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
}
Object.defineProperty(jsonObj, variableName , {
get: function() {
return jsonObj.eventRegisteredVariable[variableName] },
set: function(value) {
jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
});
}
Another possible solution can be "Object.keys(this)".... This will give you all the variable names in an array.

Categories

Resources