How to access Object's property itself while defining it? [duplicate] - javascript

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 4 years ago.
I am trying to dynamically use the previous property's value for calculation of next property.
I have a function like this in Typescript:
MacroGenerator(calories) {
this.caloriedata['macroarray'] = [
{
name: 'Low Carb, High Fat',
pmacro: (Math.round(calories*220.46226218100)/100),
pcals: (4*this.caloriedata['macroarray'][0].pmacro), // THIS IS HOW I TRIED ACCESSING THE PROPERTY AND GETTING ERROR
fcals: (calories*0.3),
fmacro: (Math.round(this.caloriedata['macroarray'][0].fcals/9)/100),
ccals: (calories-this.caloriedata['macroarray'][0].pcals-this.caloriedata['macroarray'][0].fcals),
cmacro: (Math.round(this.caloriedata['macroarray'][0].ccals/4)/100),
}
]
}
I suppose the object isn't instantiated as of when I am trying to access.
Is there any way to access it?

You can use Javascript Getters
From MDN
Sometimes it is desirable to allow access to a property that returns a
dynamically computed value, or you may want to reflect the status of
an internal variable without requiring the use of explicit method
calls. In JavaScript, this can be accomplished with the use of a
getter
var obj = {
a: 4,
get b() {
return this.a * 2;
}
}
console.log(obj.b)

Related

how to use 'this" inside a singleton object in JavaScript properly? [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 1 year ago.
var a={b:44,c:this.b+1};
I want c to be b+1 or 45 in this case. but when I try this, I get Cannot read property 'b' of undefined error.
In JavaScript, when creating an object, the execution context doesn't change. Hence, the this value is picked up from the top-level in your case. Or to articulate in a different way, you can't access the properties of the object if it's not finished initializing yet.
The actual solution to your problem might be:
var a = { b: 44 };
a.c = a.b + 1;

Why are't Object related methods inside the Object prototype? [duplicate]

This question already has answers here:
Why were ES5 Object methods not added to Object.prototype?
(2 answers)
Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?
(3 answers)
Closed 3 years ago.
There are methods like Object.values fo Object.keys, but why aren't these methods inside the object's prototype? Is there a good reason for this?
Example:
const user = { name: 'John', role: 'admin' };
const keys = user.keys() // instead of Object.keys(user);
const values = user.values() // instead of Object.values(user);
Because everything is an object in JavaScript. If you add a method to the Object's prototype, it would be inherited to everything, it can't (or shouldn't, as it then hides the original method) be used as a name of a custom method. That means that if the Object.prototype would get polluted with a lot of methods, it would make the choice of property names more difficult:
1..keys() // Did you expect this to work?

Self assign properties in an object? [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Can I reference other properties during object declaration in JavaScript? [duplicate]
(7 answers)
Closed 8 years ago.
I am trying to initialize an object and and assign a property of its own to one of the properties.
But my syntax is incorrect.i am referring to the following line:
PCMACUrl = genericURL + "/test"
i have tried
testList[0] = {
executionTimeSec:60,
genericURL:"www.gmail.com",
comments: "",
PCMACUrl = genericURL + "/test"
};
After re-reading all together I believe this is what you are looking for:
(added after init, yes, I know, but it's clean and simple :)
var data = {
'PropA': 1,
'PropB': 2,
'PropC': 3
};
data.PropD = data.PropC+5;
console.log(data); //Object {PropA: 1, PropB: 2, PropC: 3, PropD: 8}
Or, another way to look at it:
if it is possible use backend to generate the object you would like
probably you could also just get rid of same data in same object and use it differently when you call it (referencing to first object propertie and adding second on-the-go:
.../ = data.PropC+anotherData.PropA /...

Translating literal object into object's properties [duplicate]

This question already has answers here:
How to duplicate object properties in another object? [duplicate]
(16 answers)
Closed 8 years ago.
Given this object:
var myObject = {name: 'David', date: '11/13/2014'};
I want my constructor to set its object properties based on myObject:
function myClass(_object){
// set given object's properties here
}
I want to set the properties through a loop, so I wont have to set every property by hand - because the object will be dynamic.
I'm looking for a cross-browser solution.
Perhaps what you want is this:
function MyClass(_object) {
for (var p in _object) {
if (_object.hasOwnProperty(p)) {
this[p] = _object[p];
}
}
}
Don't forget to use new:
var obj = new MyClass(myObject);
Fiddle

Create javascript object using constants with dots as property [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 8 years ago.
I have an object holding some of my program constants so that I can use it in all of the source code files. The constants object is something like this:
CONSTANTS = {
THING_TYPE: 'type',
THING_INFORMATION: 'information',
THING_DESCRIPTION: 'description',
THING_NAME: 'name',
manyOtherConstants
}
And I want to create objects using a similar notation and using the value of the constants as a property of the object; this is what I'm trying to do:
var myObject = {
CONSTANTS.THING_TYPE: 'whateverType',
CONSTANTS.THING_INFORMATION: {
CONSTANTS.THING_DESCRIPTION: 'whateverDescription',
CONSTANTS.THING_NAME: 'whateverName',
}
}
The problem is that I cannot use the constants in that way. Javascript says:
'SyntaxError: missing : after property id'
Is there any way of doing what I am trying to do using that notation? Or is the only thing that I can do is the following?
var myObject = {}
myObject[CONSTANTS.THING_TYPE] = 'whateverType';
myObject[CONSTANTS.THING_INFORMATION] = {};
myObject[CONSTANTS.THING_INFORMATION][CONSTANTS.THING_DESCRIPTION] = 'whateverDescription';
myObject[CONSTANTS.THING_INFORMATION][CONSTANTS.THING_NAME] = 'whateverName';
No you cannot do that using object literal initialization syntax.
So the only way is to use what you do in the second case - using [...] notatin.

Categories