Assign custom property to dynamically generated JS functions - javascript

I'm trying to setup a speed test for functions. It works when I pass in a function directly, but I'd like to offer co-workers a form to cut and paste their own.
function sendTest() {
//fName, fContent
var fName = document.getElementById("fName").value;
var fContent = document.getElementById("fContent").value;
var f = new Function(fName, fContent);
f.name = fName;
testTime(f);
}
testTime() is the function to evaluate performance, and evaluating time of execution is working correctly from sendTest(), but I can't access the function name from testTime() to display the function name with the results. f.name and f.fName both come up as undefined.
A function is an object, right? So I should be able to apply a name propery to it?

This seems like a much simpler answer for your specific problem than the what someone else marked your question a duplicate of.
In ES6, there is a built-in .name property of a Function which is NOT writable so that's why you can't assign to it (link to specific section of draft ES6 spec). You should be able to use a different property name if you want to assign a name the way you are doing so.
Working demo using a different property name: http://jsfiddle.net/jfriend00/6PVMq/
f = new Function("log('Hello')");
f.myName = "sayHi";
function testFunc(func) {
log("function name is: " + func.myName);
func();
}
testFunc(f);

Related

How to use a variable as a function parameter in Javascript?

I'm a big noob at JS,so if my question is hard to understand then sorry😂.
I'm writing a program in JS(Electron) that provides a user interface for another program I made in C++, so I'm basically rewriting it in JavaScript.
I want to use this JSON variable(or whatever it's called) in my code.
var ShowSecondsInSystemClock = '{"name":"ShowSecondsInSystemClock","Description":"Patches the System Tray clock to show seconds","ExplorerRestartRequired":"true","category":"UI-Tweaks","badges":"UITweaks"}'
Then I would like to use this function where the parameter of the function "ShowSecondsInSystemClock" is.
function TweakParser(TweakName, NeeddedReturn) {
if (NeeddedReturn == "Description") {
//I'm trying to use TweakName as the parameter of parse(),but it only
//accepts the name of the Tweak directly
var NeeddedTweakInfo = JSON.parse(TweakName)
return NeeddedTweakInfo.Description
}
}
Because there will be many Tweaks, the usecase of this particular function is for example
//I use a non-existing tweak here for the example
TweakParser("RemoveArrowsFromShortcut","Description")
What I want TweakParser to do now is use RemoveArrowsFromShortcut as the parameter of JSON.parse() but it only accept the name of the JSON variable directly and when I input the name of the first parameter of the TweakParser() function it gives me an error, because the parameter(a variable) itself is not a JSON variable (or whatever it's called like).
So my question to you is:
How can I use the string that the first parameter of TweakParser() contains as a parameter for the JSON.parse() function?
You need to create mapping
like a schema 'key': variable
example:
{
'RemoveArrowsFromShortcut': ShowSecondsInSystemClock
}
Full example:
var ShowSecondsInSystemClock = '{"name":"ShowSecondsInSystemClock","Description":"Patches the System Tray clock to show seconds","ExplorerRestartRequired":"true","category":"UI-Tweaks","badges":"UITweaks"}'
var mapping = {
RemoveArrowsFromShortcut: ShowSecondsInSystemClock
};
function TweakParser(TweakName, NeeddedReturn) {
if (NeeddedReturn == "Description") {
var NeeddedTweakInfo = JSON.parse(mapping[TweakName]); // PAY ATTENTION HERE
return NeeddedTweakInfo.Description
}
}
var result = TweakParser("RemoveArrowsFromShortcut","Description")
console.log('result', result)

Are all of these 3 methods of setting a property in localstorage valid?

I know only one way of setting localstorage in HTML5
localStorage.name = "Peter Martin";
But, in the following discussion I found that there are 2 other ways to set localstorage.
localStorage - use getItem/setItem functions or access object directly?
localStorage.setItem(city, "New York");
localStorage[country] = "USA";
However, when I tried all 3 in the example below, seems the first works fine but issues with the other 2 methods. Can someone explain me out if all 3 methods are valid?
<html>
<head></head>
<body>
<button onclick="alpha()">Click Me</button>
<script>
function alpha(){
localStorage.name = "Peter Martin";
localStorage.setItem(city, "New York");
localStorage[country] = "USA";
}
</script>
</body>
</html>
As, there is some sandbox issue with StackOverflow, I am posting error image, as below:
This comes down to basic JavaScript syntax.
When you call localStorage.setItem(city, "New York");, you are referring to an identifier, city, which is not defined in the current scope. You should either define a variable named city, or just use the string "city" directly.
The same goes with localStorage[country] = "USA";. country is not defined in this scope, so the JavaScript engine throws an error.
Can someone explain me out if all 3 methods are valid?
Yes they are (ish). localstorage like pretty much everything in Javascript is an object. You can access properties in an object in two ways:
object.property
object['property']
See Property accessors in Javascript MDN. So there is no reason why you can't access properties of the localstorage object using property accessors as the above.
localStorage.setItem("city", "New York");
Is a method on the localstorage object that:
The setItem() method of the Storage interface, when passed a key name
and value, will add that key to the storage, or update that key's
value if it already exists.
MDN
So this is a valid way to "add that key to the storage, or update that key's
value if it already exists". Your having problems with this method because your passing an incorrect parameter city that doesn't exist. I believe you meant "city". As covered in this answer
You can break it down into
1> properties or values
localStorage.name = "Peter Martin";
localStorage["name"] = "Peter Martin";
The 2nd version allows you to use a JavaScript variable. But is harder to read because one needs to determine what value is in the variable.
IE
var tag= "name";
localStorage[tag] = "Peter Martin";
and
2> methods or functions that get / set value; etc.
localStorage.setItem("name", "Peter Martin");
vars allowed,
var obj = "name";
var value = "Peter Martin";
localStorage.setItem(obj, value);
With methods there are the .prototype goodies, which include things like .bind() that allows you to say do something when you call setItem. But generally when I want to do something after setting a property I do it on the very next line; I Keep it simple and readable.
I'm not sure why I would ever need to use the methods. But, on a modern system there should be no measurable difference in speed.
Maybe using methods would allow two tabs open at the same time to synchronize data between tabs?
There are situations in loops that change values of properties and either methods or properties works, I don't recall the details; but unlikely to need that with a localStorage string.
Now I recall, why a method or function is sometimes needed.
This fails using a property. (always returns 10 the last value of i)
var elements = document.getElementsByTagName('input');
var n = elements.length; // assume we have 10 elements for this example
for (var i = 0; i < n; i++) {
elements[i].onclick = function() {
console.log("This is element #" + i);
};
}
This works using a function
var elements = document.getElementsByTagName('input');
var n = elements.length; // assume we have 10 elements for this example
var makeHandler = function(num) { // outer function
return function() { // inner function
console.log("This is element #" + num);
};
};
for (var i = 0; i < n; i++) {
elements[i].onclick = makeHandler(i+1);
}
So if you are going through a long list and want to cancel then return to it using localStorage use the method.
Even though the localStorage may not require a method. Our subconscious brain recognizes patterns. And the loop with a property value pattern triggers a warning, anxiety because of how long it takes to find it, even though the details are not recalled. Though it would work since it does not store a reference to the variable it only stores static strings.
To program at max speed, people need to follow the patterns that they know work. Methods resolve the value of the value at the time the method was called.
<html>
<head></head>
<body>
<button onclick="alpha()">Click Me</button>
<script>
function alpha(){
localStorage.name = "Peter Martin";
localStorage.setItem("city", "New York");
localStorage["country"] = "USA";
}
</script>
</body>
</html>

access of an array inside another array in javascript

i have two arrays defined like these
var theory= new Array();
var first;
var second;
function arrTheory () {
this.first= first;
this.second= second;
}
var subject= new Array();
...
function arrSubject () {
...
this.theory= theory;
...
}
how can i access to the elements in the theory array inside the bigger one?
I've tried
subject[0].theory.first;
but it doesn't work while
subject[0].name;
which is another field of the big array works fine. what i've missed?
I think the point is, you have an array with element as "obj" and added to another array.
So to access to a you could try
subject[0].theory[0].first;
I mean access to element of array by index and them access to the element of the object.
Ok, I have a good guess given the information you've provided.
theory in subject[0].theory is an array, right? How come you are using it like subject[0].theory.first? You should use an indexer like subject[0].theory[0].
In the code you showed us (before any potential edits), you don't add anything to the var theory= new Array();
Also beware to make sure that this is what you really expect. In JavaScript, the context of this changes depending on context of the caller and that's confusing sometimes.
subject[0].theory[0].first;
try that.
Using this in arrTheory() and arrSubject() will cause a syntax error because they are functions not objects and you need rather to set those properties to theory and subject arrays instead so you must use the correspondent array name instead of this like following:
var theory= new Array();
var first = "first";
var second = "second";
function arrTheory () {
theory.first= first;
theory.second= second;
}
var subject= new Array();
function arrSubject () {
subject.theory= theory;
}
arrTheory();
arrSubject();
alert(subject.theory.first + " / " + subject.theory.second);
then you can access first and second properties like this:
subject.theory.first
subject.theory.second
in the code above property name is not set in subject, if it's already set in the original code you can call it like this:
subject.name
jsfiddle

How to use parameters from another function [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Get actual HTML values using javascript
so i have two problems here. let me explain what i am trying to do first. I have a page that has values that change on it, however i want to grab the values before they change, keep them, and then once a button is pushed, change the html to the original html. Now first of all my biggest problem is that when i try to uncomment the initial2 function, it just doesnt work. it brings me to the webpage then for some reason the html url tries to change and it says it can not find the page. the second, and more understandable problem for me, is that the function previousaccept i cant get to use the values from the previousnames function.
function previousnames()
{
name= document.getElementById('name').innerHTML;
imagetitle= document.getElementById('imagetitle').innerHTML;
location=document.getElementById('location').innerHTML;
similarities = document.getElementById('similarities').innerHTML;
type = document.getElementById('type').innerHTML;
cost = document.getElementById('cost').innerHTML;
date = document.getElementById('date').innerHTML;
pictureid = document.getElementById('pictureid').src;
}
function previousaccept(name,imagetitle,location,similarities,value,type,cost,date,pictureid)
{
document.getElementById('name').innerHTML = name;
document.getElementById('location').innerHTML = location;
document.getElementById('similarities').innerHTML = similarities;
document.getElementById('type').innerHTML = type;
document.getElementById('cost').innerHTML = cost;
document.getElementById('date').innerHTML = date;
window.alert(pictureid);
document.getElementById('pictureid').src = pictureid;
}
window.onload=initial();
function initial()
{
myvalues;
previousnames;
}
/*
function initial2()
{
myvalues;
previousnames();
}*/
If you set the location (which is window.location), then the browser will go to a new web page. That's what you're doing in the previousnames() function with this line:
location=document.getElementById('location').innerHTML;
If you're trying to have a global variable named location, then give it a different name that isn't already used by the browser.
Also, you should explicitly declare any global variables you intend to use outside of your functions rather than use implicitly declared variables like you are which makes your code very prone to errors.
I think this will do what you want. The key is to make sure that the scope of the variables you are trying to store is such that the functions have access to them all. I do this by defining an empty object dataStore at the start of the onload function, and also defining the 2 other functions within the onload function. Putting all the stored data in a single object is convenient and avoids naming problems (such as the window.location problem noted by the previous answer.)
window.onload = function() {
var dataStore = {};
function getInitialData() {
dataStore = {
name: document.getElementById('name').innerHTML,
imagetitle: document.getElementById('imagetitle').innerHTML,
// and so on...
}
}
function resetData() {
document.getElementById('name').innerHTML = dataStore.name;
document.getElementById('imagetitle').innerHTML = dataStore.imagetitle;
// and so on...
}
getInitialData();
//... then later when you want to reset all the values
resetData();
}​

Javascript Computed Values With Arrays

Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']

Categories

Resources