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

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;

Related

Member undefined when calling function indirectly [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 2 years ago.
class Hello{
constructor(member) {
this.member = member;
this.name_function_map = {"print_member" : this.print_member};
}
print_member(){
console.log(this.member);
}
}
let h = new Hello(2);
h.print_member();
//=> works as expected
h.name_function_map["print_member"]();
//=> why is it h. member undefined
the output is:
2
undefined
can someone please enlighten me, why is calling the member function of Hello through a reference stored in a map any different than calling it directly?
And how may i work around that.
When you execute:
let h = new Hello(2);
h.print_member();
The this keyword inside the print_member method will be equal to h (the object instance). That is correct. But, when you execute:
h.name_function_map["print_member"]();
or equally
h.name_function_map.print_member();
the this keyword inside the print_member method will be equal to h.name_function_map, which is:
{"print_member" : this.print_member}
Obviously, this object does not have a member property, and that's why you are getting undefined.

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

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)

how object.constructor() works? [duplicate]

This question already has answers here:
Javascript constructor return values [duplicate]
(2 answers)
Closed 5 years ago.
Recently I have attended one interview, Interviewer asked one interesting question have a look
function MyClass(){
this.a = 10;
return 20; // Interesting part
}
var obj1 = new MyClass();
console.log(obj1.a); // 10 works as expected.
console.log(obj1.constructor()); // 20 later I found this
how will you access return value(20) from obj1?
I found the answer after looking proto of the obj1.
obj1.constructor() Works as expected
Please help me to understand this.
See mdn:
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
The 20 goes nowhere and cannot be accessed. It isn't an object, so the instance of MyCass is returned instead.

“this” inside an Object pointing to an empty Object [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 5 years ago.
So I have this JavaScript code:
var obj={
a: “Chris”,
b: this
};console.log(obj.b); //{}
The console.log return an empty object rather than the object with variable a and b.
Anyone know why?
Thank you very much!
If this code is in the global scope, which I assume it is, this points to the global object (whatever it is). If you want it to point to the object itself, you cannot do it in the literal, you need to assign it later (after you create the object itself).

JavaScript Calling Object Syntax [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I need to know why this isn't working. My Javascript code accesses a variable in an object. But it appears not to be working, partly because I can't figure out the syntax.
var obj = {
size:"small",
big:false,
thing:true
}
alert(obj[size]);
I'm just not sure if I got the syntax right…
This will work here.
obj.size //returns small
OR
obj["size"] //returns small
OR
var my_var = "size"
obj[my_var] //returns small
You can reference object values either by:
obj["size"]
or
obj.size
However, there is an exception. For instance, if you have following object with a number key: (Note: key is still a string even if it's defined this way):
var obj = {
1: true
};
You can retrieve it's value only by using: obj["1"]
Hence, using obj.1 will cause a syntax error.
Therefore, your code works if you change it to e.g.: alert(obj["size"]); but I prefer to use console.log(obj["size"]); for debugging. At least, if you are playing with node.js as your tags indicates.
Cheers.

Categories