This question already has answers here:
calling eval() in particular context
(18 answers)
Closed 7 years ago.
I have some trouble using the Object properties. I want to evaluate an expression within the myObject context to avoid using the myObject.property.
My final goal is to evaluate a more complex expression like 'property1+property2' instead of 'myObject.property1+myObject.property2'.
I have tried the call method to change the context but, it doesn't seem to see the Object properties in the passed context(i.e. the Object containing the properties)(see the last line of the code below generating the error).
var myObject = {
property1: 20,
property2: 5000
};
print(myObject.property1); // return 20
print(eval.call(myObject,property1)); // ReferenceError: property1 is not defined
Is there any way to use the Object properties without the usage of this. or myObject. prefix?
Well, there's with statement which is deprecated and you probably shouldn't use it too much, but in this case maybe it wouldn't be considered harmful:
with(myObject){
console.log( property1 ); // 20
console.log( eval('property1') ); //20
console.log( eval('property1+property2') ); // 5020
}
http://jsfiddle.net/f7d1b79b/1/
Related
This question already has answers here:
Using a string to access a variable
(3 answers)
Closed 3 years ago.
I have a JS function as below
// A simple array where we keep track of things that are filed.
filed = [];
function fileIt(thing) {
// Dynamically call the file method of whatever 'thing' was passed in.
thing.file();
// Mark as filed
filed.push(thing);
}
Now, function fileIt(thing) is working well when called as below
fileIt(AuditForm);
Whereas, its giving error at line thing.file(); when i am trying to pass a variable like below
var formID = obj.id;
fileIt(formID);
Variable formID has same value and i.e. "AuditForm" what's wrong here. Kindly suggest.
If obj.id is the string AuditForm, then you have no choice but to use dynamic property notation on the global window object, or use eval if you didn't declare AuditForm with var on the global scope:
If you declare AuditForm with var on the global scope:
fileIt(window[formID]);
If you don't:
fileIt(eval(formID));
Do note that eval is a very poor option, as if obj.id can be interpreted as other code, e.g. another eval call which will be evaluated, then malicious operations can be performed. Example:
const obj = {
id: "eval('alert(\"Inside an eval script!\")')"
};
eval(obj.id);
This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 5 years ago.
In a simple JS object like this:
var LeadserData = {
agent_id: 2,
object_queries: {
emails: {
url: "/manual_emails/",
method: 'GET',
send_data: {
the_id: this.agent_id
}
}
}
}
it is obviously possible to access the agent_id simply like this:
LeadserData.agent_id = 100;
alert(LeadserData.agent_id);
This obviously returns 100. But why does not the internal reference of this.agent_id work?
alert((LeadserData.object_queries.emails.send_data.the_id));
I was expecting this to come out as "100" as well, but instead it is undefined. The whole fiddle is here: https://jsfiddle.net/h88zc5nw/1/
What is the explanation for this behaviour, and how can I tweak this to return the expected 100.
First of all, you are using an object literal. You can't use this inside an object literal, at least it won't be what you think it is. It will be whatever this available while the object literal is constructed.
Second, even if we assume that the above works, numbers are native types, they won't be shared via their references. So changing LeadserData.agent_id won't affect LeadserData.object_queries.emails.send_data.the_id even if you have assigned one to the other. Native types are copied on assignment, not passed around using a reference (like you would do with an object).
This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();
This question already has answers here:
Does node.js have equivalent to window object in browser
(2 answers)
Closed 6 years ago.
I know with browser-run JavaScript, I could use window[varName]=value; to set global variables. I seem to remember there being a function to accomplish this in Node JS, but I'm not sure what it is.
If it helps, I'm aiming to set all the properties of an object as separate own variables.
In Node.js the global variables are stored in the global object, I think...
Then it'd be so:
global[varName] = value;
// or...
global.varName = value;
I think you're confusing something. Maybe you want to initialize a object constructor expression.
{ property: "string, or anything else" }
// this expression returns a object that can be assigned
// everywhere, but when assigned, turns a reference
If you want to get/set properties in this object you must do the same thing you were doing before, index the object with the keys [...] or ., then you can optionally assign (set) the object's property with =, else it'll be returned.
This question already has answers here:
JavaScript Object Literal Notation Internal Variable Pointing [duplicate]
(3 answers)
Closed 9 years ago.
I am trying to set and later access a variable using object literal notation. I need to use this variable in subsequent code so I want to set it here just once.
When I run this code at jsFiddle, I get the error that HalfWidth is NaN. How do I set and access this variable from here?
var $LIST = {
FullWidth: 120,
HalfWidth: this.FullWidth / 2,
exit: function () {}
};
alert($LIST.FullWidth);
alert($LIST.HalfWidth);
http://jsfiddle.net/7JcaQ/
this have zero relevance to your situation - it is only defines context object for method call. Additionally, you cannot reference $LIST in its own definition, because it doesn't exits until definition ends.
Write:
var $LIST = {
FullWidth: 120,
exit: function () {}
};
$LIST.HalfWidth = $LIST.FullWidth / 2
(For the note, you're getting NaN, because outside of method call this is most often refers to global object, which naturally, most often don't have any numeric value in its .FullWidth property. Dividing this by 2 produces NaN.)