Let's say I want to make a JavaScript function which sets variables to numbers, using the following format. It would not work, but why exactly? How could it be made to work?
function variableSet(varName, varValue) {
varName = varValue;
}
The idea is to create a variable with the name used as a parameter, and give it the value of the second parameter. How could this be done?
Not sure I understand your question. But if you need to give a variable name and it's value to overwrite the variable, it can be done like that:
this[varName]=varValue;
In this case "this" is your context, in which variable was defined. If you need to provide the other context, you can put it as other parameter, so function will look like this:
function variableSet(varName, varValue, context) {
context[varName]=varValue;
Related
I wanna pass in some variables to my functions like int, string, and etc. I'm a C# developer and is very new in JS.
In C# we normally call a function with:
function computeGrade(int grade)
{
...
}
computeGrade(90);
I understand that js uses var that can either be a string, int, etc.
However when I try:
function ComputeGrade(var grade)
{
...
}
it gives me an error that it failed to initialize the function.
Forgive me for being too naive with js.
Thanks a ton!
In js variables are just untyped name bindings. So you don't need to tell what a variable is capable of storing. Actually It just refers to any type of value.
function ComputeGrade(grade)
{
...
}
So here, grade is just a name binding. It does not matter what kind of value you pass this function. It will bind to grade variable.
Use var for declaring local variables. For function arguments just use the param name without var.
I'm trying to figure out (not successfully yet) if it's possible to check if js function I'm trying to mock with spyOn (jasmine) was called with the exact parameters I expected, for example consider function:
foo = function(date, array) {};
So far I can only make sure that the array was indeed passed like this:
spyOn(bar, 'foo').and.returnValue(somePromise.promise);
somePromise.resolve;
//call some function that calls 'foo' eventually...
expect(bar.foo).toHaveBeenCalledWith('10/12/2100', []);
I need to check if the array passed to this function was empty, how can I achieve this? Also if it's possible, how can I check if array passed to this function contained the string I wanted?
Thanks!
Replace and.returnValue with and.callFake, then pass in a function that stores the arguments before returning the promise. Then the arguments can be used for later expect tests.
I don't know Jasmine, so this will probably not be the answer you're looking for.
On the other hand, it is a doable work around that you can implement in the mean time while you await your real answer.
If you have control over foo, then in the foo method you can tell it to set a global variable to its input parameter:
var fooParam;
var foo = function(array){
fooParam = array;
}
Then in your other code, you can do:
if (fooParam != null){
if (fooParam.contains(yourString)){
//I'm not sure if "contains" is actually a method or not,
//but that's really a separate issue.
}
}
So you set the global variable fooParam in the foo method and then you can use it later to do checking.
So there's a potential problem in that you might not have control over foo, such as if it's a system method. To work around that, replace all calls to foo with something like foo2, which you would define to have the same parameters and all it does is call foo and set the global variable. But if you have control of foo, then you don't need to do this.
The other potential problem is that foo will be called multiple times (such as if it's called within a loop). To circumvent this, you might make the global variable be an array list and have foo add its parameters to the array list instead of setting the variable. But if it's not called within a loop, or not called multiple times before it can be processed, then you don't need to do this.
I hope this helps while you're looking for the real answer
If i have a function defined inside some object as in :
var myobject={
myfunction:function(){//mycode here}
}
usually you can access the function using:
myobject.myfunction()
but what if i want to use
myobject["myfunction"]
trying so , actually the function did not get called , how can i call the function using brackets notation ?
Use it like. You were very close
myobject["myfunction"]();
You can also do this
var myfuncname="myfunction";
myobject[myfuncname]();
The two forms
myobject.myfunction;
and
myobject["myfunction"];
are equivalent as long as you only use a fixed string to access the member (using a computed value is a different matter, then you must use the second form). Both lines result in the function-object-member myfunction which you can assign to a variable if you like, and calling that:
var myfunc = myobject.myfunction;
myfunc();
Note that assigning it to the variable breaks the this variable, so you might not want to do that if you're doing OOP.
And as you noted, calling a function means adding () with an argument list afterwards, it doesn't matter that the function is acquired through an expression, so either:
myobject.myfunction();
or
myobject["myfunction"]();
I'm a novice at JavaScript so please forgive any incorrect terminology/understanding.
I'm trying to extract a variable thebest from a callback function function(thebest,all) within a method ec.get.
I've done a little reading up on scope and I was expecting the code below to work, but it appears the thebest variable outside the function is in a different scope than the variable inside the method's function.
var thebest = 0;
ec.get("id", function(thebest,all) { });
alert(thebest);
I have also tried using a different variable name on the outside but it made no difference. How can I access the value of the "innermost" thebest variable from outside the method and its function? Thanks!
It looks like there are several issues here:
Issue 1: If you want to change the value of theBest in the callback function, you can't change it by passing it as a parameter. Simple variables are passed by value so the original isn't changed if you change it in the function.
Issue 2: Assuming ec.get() is a networking operation, it's probably asynchronous which means that the callback function you pass it isn't called until much later. That means, the completion callback function will not have executed yet when your alert fires. So, it won't have changed anything yet.
Issue 3: You can't pass arguments to a callback the way you have it declared. That will define those arguments, but unless ec.get() is going to pass arguments just like that, the arguments won't actually be there when it's called. Remember, it's ec.get() that calls your function internally. It alone decides what arguments your callback gets. You can't change that.
Issue 4: When you declare an argument for your function with the same name as a local or global variable (thebest in your example), you create a name conflict which causes the argument to take over that name for the scope of your function and make the higher level variable inaccessible. In general, it's a bad idea to name a function argument with the same name as any other variable that is in scope. It just asks for you or other people reading your code to get confused and make wrong assumptions about what is getting modified or read when using that name.
One way to do this is as follows:
var thebest = 0;
var all = "whatever";
ec.get("id", function() {
// use the arguments "thebest" and "all" here which are available
// from the higher scope. They don't need to be passed in
alert(thebest);
alert(all);
});
// you can't alert on the value of thebest and all here because
// an asychronous callback won't have yet been called and
// won't have yet modified those values
If the callback is something that executes promptly (not async) then you can simply assign it out to a differently named variable. For example
var theBest = 0;
ec.get("id", function(theBestArg,all) { theBest = theBestArg; });
alert(thebest);
Your problem is that you are redeclaring theBest as an argument for your function.
var thebest = 0;
ec.get("id", function(theNewBest,all) { theBest = 'new value' });
alert(thebest);
Ok, I don't know how to actually ask this question without showing it. (Also explains why I can't figure out how to search for it on Google.)
Given the following like of code:
dijit.byId('leftNavigationPane').onLoad = function(){setSecondaryNav(url.secondaryNavId);};
I want the variable url.secondaryNavId to be evaluated, so what I really want is it to be treated something like this:
dijit.byId('leftNavigationPane').onLoad = function(){ setSecondaryNav('item1'); };
I am sure there is probably a better way to do this, so feel free to suggest something.
Don't use eval!
You can use a self-invoking function and closures as follows:
dijit.byId('leftNavigationPane').onLoad = function(id){
return function(){ setSecondaryNav(id); };
}(url.secondaryNavId);
This will execute the outer anonymous function immediately (at runtime), passing the url.secondaryNavId parameter, which will then create a closure that the inner anonymous function will use (so id will always contain the assignment-time value of the url.secondaryNavId property).
There is the JavaScript eval() function.