This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
Problem: I want to make a variable inside a function as a global variable
This works:
var x;
function myFunction() {
x = 999;
}
myFunction();
console.log(x);
But this one doesn't work while trying to declare a global variable from API Result
webOS.service.request(url, {
onSuccess: function (data) {
var serial = data.idList[0].idValue;
var udid = serial; // This is the variable that I want
callback(udid); // Trying to get this udid out of this API call
},
});
var sn;
function callback(udid) {
sn = udid; // I want this as my global variable
}
callback(udid); // produces an error which says udid not defined
console.log(sn); // undefined
How can I make var sn as global variable? Thanks in advance
It's because udid is not defined in the scope you're calling callback in - you're calling callback in your onSuccess function, so you don't need to call it again. You also need to place your console.log inside your callback function:
webOS.service.request(url, {
onSuccess: function (data) {
var serial = data.idList[0].idValue;
var udid = serial; // This is the variable that I want
callback(udid); // Trying to get this udid out of this API call
},
});
var sn;
function callback(udid) {
sn = udid; // I want this as my global variable
console.log(sn);
}
Related
This question already has an answer here:
Why can’t I assign values to a variable inside a named function expression with the same name?
(1 answer)
Closed 3 years ago.
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
If You run this example you can see we can not reassign to functionExpressionName anything.
But this is also interesting we can reddeclare functionExpressionName and after this we can assign anything to functionExpressionName
var functionVariable = function functionExpressionName() {
function functionExpressionName() {
}
functionExpressionName = 1;
console.log(functionExpressionName); // 1
};
functionVariable();
If you enable strict mode, the error becomes a bit clearer:
'use strict';
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
Uncaught TypeError: Assignment to constant variable
The function name is un-reassignable inside the function, but you can create a new variable with the same name inside the function body. One way of looking at it is that the function name is declared with const just outside the function body:
var functionVariable = (() => {
const functionExpressionName = function () {
functionExpressionName = 1; // Clearly wrong - functionExpressionName is a const
// but it would work if you declared a *new* variable,
// which has a different lexical binding
console.log(functionExpressionName) // function
};
return functionExpressionName;
})();
functionVariable();
This isn't exactly what happens, but it's pretty close.
This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 6 years ago.
Have a function assigned to a variable
var sq = function a(s){return s * s};
Now if i call sq(4) i am getting the result as 16 but if i try to call using the function name a(4) it throws an error "a is not defined"
Can we not call the function by its name once it is assigned to a variable.?
No, because you're using an assignment. You can just do var fn = function () { } or var fn = ()=> { } and get the same thing.
If you created the function and then assigned it to a variable, you could do both.
Basically,
function fn() {...}
var myFunc = fn;
You could then do both:
myFunc();
fn();
This question already has answers here:
dynamically call local function in javascript
(5 answers)
Closed 8 years ago.
I'm having a difficulty calling a function inside of another function when its name is in a variable:
var obj = {}
obj.f = function() {
var inner = {
a: function() {
function b() {
alert('got it!');
}
b(); // WORKS AS EXPECTED
x = 'b';
[x](); // DOESN'T WORK, NEITHER this[x]() window[x](), etc.
}
}
inner.a();
}
obj.f();
I tried prefixing [x]() with different scope paths but so far w/o success. Searching existing answers did not turn up anything. It works with this[x]() if b() is placed directly inside object inner. I would like to keep b() as a function inside function a() because of variable scope in function a(), otherwise I would need to pass many parameters to b().
////
Re duplicate question: Quentin provided a more elegant answer in this thread imo.
There is no sensible way of accessing an arbitrary variable using a string matching the name of the variable. (For a very poor way to do so, see eval).
[x](); // DOESN'T WORK
You're trying to call an array as a function
NEITHER this[x]()
The function isn't a property of the inner object.
window[x](), etc.
Since it isn't a global, it isn't a property of the window object either.
If you need to call a function based on the value of a string variable, then organise your functions in an object and access them from that.
function b() {
alert('got it!');
}
var myFunctions = {
b: b
};
x = 'b';
myFunctions[x]();
Try this. Currently you are assigning string to variable x, instead of a function variable.
x = b;
x();
The problem is with your assignment
use x = b instead of x = 'b' to assign the function object as the latter just assigns the string into x.
Once you fix your assignment you can invoke the function as
x();
a.x();
a[x]();
etc.
You should make array for the function and then access using name in your variable as follow:
var obj = {}
obj.f = function() {
var inner = {
a: function() {
// set up the possible functions:
var myFuncs = {
b: function b() {alert('got it!');}
};
//b(); // WORKS AS EXPECTED --> commented this code
x = 'b';
myFuncs[x]();
}
}
inner.a();
}
The function declaration b will be captured in the closure of the anonymous function expression assigned as a.
When var is used in a closure, there is no (available in JavaScript) Object which gets assigned a property similar to what happens with window in the Global Scope.
Writing a function declaration effectively vars the name of the function.
If you really want to access a variable (i.e. b) by String, you will either need to create an Object which holds b similar to what you've done for a, or (and possibly dangerously) rely on an eval to convert "b" to b.
If you can't create the whole Object ahead-of-time, you can use this format
/* in (higher?) scope */
var fnRef = {};
// now when you
function b() {/* define as desired */}
// also keep a ref.
fnRef['b'] = b;
// fnRef['b']() will work **after this line**
let's say your code is like this:
//instead of x = 'b'
x = function(){}
then your solution could be like this:
var obj = {}
obj.f = function() {
var inner = {
a: function() {
function b() {
alert('got it!');
}
b(); // WORKS AS EXPECTED
//you can define it as a variable
var x = function(){};
//and call it like this
x();
//or define it like this
this[x] = function(){};
//and call it like this
this[x]();
//but you are creating an array [x] which is not a function
//and you are trying to call an array????
[x](); // DOESN'T WORK, NEITHER this[x]() window[x](), etc.
}
}
inner.a();
}
obj.f();
This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a function in JavaScript:
function main() {
console.log(this);
}
How come this logs Document? Surely it should log function main?
If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?
Thank you!
Hey you can do something like this.
But then this would look something like a class object.
<script>
function main() {
this.testVar = "124";
}
var testMain = new main();
alert(testMain.testVar);
</script>
The alternative is that you just create a normal global variable.
The way i am taking the code is a more class object way.
Hope i could help :)
The this keyword references the context of the function, not the function itself.
When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).
Example:
var o = {
name: 'myObject',
fn: function(){ alert(this.name); }
};
o.fn(); // alerts "myObject"
As a function is also an object, you can add properties to it:
function main() {
}
main.varName = 42;
alert(main.varName); // shows "42"
However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.
Also, check out the module pattern
var person = function(){
return module = {
setName: function(name){
module.name=name;
}
}
};
var bill = person();
bill.setName('bill');
console.log(bill.name);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()..
It's defining a single-use function and executing it immediately. The code you provided is named the Module Pattern -- see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
var f1 = function() {
console.log('bar');
};
And you could subsequently call it like so:
f1();
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions: incrementCounter and resetCounter. You can call them like so: testModule.incrementCounter() and testModule.resetCounter()
The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.
The anonymous function is executed and the return value is assigned to the variable.