Accessing a local variable of a function from another function [duplicate] - javascript

This question already has answers here:
Accessing variables from other functions without using global variables
(10 answers)
Closed 5 years ago.
Using the following code how can I access a from inside log2?
(function() {
function log() {
var a = "string";
}
log()
function log2() {
console.log(log.a);
}
console.log(log);
log2();
})()

Variables declared with the var keyword in JavaScript are function-scoped. This means that they cannot be accessed from outside the function they were declared in without returning them. The solution is to declare the variable within your outer immediately-invoked function, which will enclose the variable and make it available to the two inner functions:
(function() {
var a;
function inner1 () {
a = 'string';
}
function inner2 () {
console.log(a);
}
inner1();
inner2(); // => logs 'string'
})()
console.log(a); // => logs undefined, because a is enclosed

Related

How can i use varaible from outer scope of the callback function [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
How do I use the variable from the outer scope of the function. I have created this simple example here
var view = {
init(){
const targetOne = document.querySelector(".targetOne");
const targetTwo = document.querySelector(".targetTwo");
var val = "outer scope";
targetOne.addEventListener('click', (e) => {
console.log('target one', val)
});
targetTwo.addEventListener('click', this.handleEvent);
},
handleEvent(e) {
console.log('targetTwo ', val);
}
}
view.init();
JS fiddle link: https://jsfiddle.net/jr7b521x/50/
For the targetOne callback I can use the variable val, but when i define a function for the targetTwo callback, that variable val is not defined in the scope. I feel like I am missing something very simple here, I refreshed on scope chaining and closure but I am not able to get it
the variable val is within the scope of the init () function
for you to get it in the handleEvent function you will need to pass it by parameter or it must be a property of the view object

Scopes at functions? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 4 years ago.
function x() {
var a = 2;
y();
}
function y() {
a += 3;
}
x();
//returns a is not defined
If i declare a function (y) outside the function (x) where it's been called, why it isn't inherit the outer function's variables and values? There's a way to solve the problem described above?
Variable a is declared as part of the function x(). That's why a is available only inside x(). To solve the problem you have to pass variable a as the function parameter:
function x() {
var a = 2;
y(a);
}
function y(a) {
a += 3;
console.log(a);
}
x();

How to access the JSON object outside the Fetch API response? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am currently having a problem accessing emoji_map outside of the then scope and I don't know how to do it.
Here's my code:
if (req) {
fetch(req).then(function(response) {
return response.json();
}).then(function(response) {
/* start to observe */
emoji_map = response.emoji_map;
console.log(emoji_map);
});
}
When I do console.log(emoji_map); outside if loop I cannot access the response assigned. Can anyone help?
I suggest you read more about JavaScript lexical scoping and closures on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures.
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
init() creates a local variable name and then a function called
displayName(). displayName() is an inner function that is defined
inside init() and is only available within the body of that function.
displayName() has no local variables of its own, however it has access
to the variables of outer functions and so can use the variable name
declared in the parent function.
What you can declare a global variable outside your fetch statement, and fill the response in that variable, say in your case
var sampleData;
if (req) {
fetch(req).then(function(response) {
sampleData = response.json();
return response.json();
}).then(function(response) {
/* start to observe */
emoji_map = sampleData.emoji_map;
console.log(emoji_map);
});
}
OR
fetch('https://davidwalsh.name/some/url').then(function(response) {
return //...
}).then(function(returnedValue) {
// ...
}).catch(function(err) {
// Error :(
});
you can try the above code or refer this

This values for arrow functions [duplicate]

This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 5 years ago.
I am trying to understand arrow functions in ECMAScript 6.
This is the definition I came across while reading:
Arrow functions have implicit this binding, which means that the
value of the this value inside of an arrow function is aways the
same as the value of this in the scope in which the arrow function
is defined!
According to the definition, I believe this for an arrow function should contain the same block level values that the arrow function was defined in.
Code:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: () => console.log(this)
}
}
console.log(test.k.testfunc);
However, I am getting this result from the code
function testfunc() {
return console.log(undefined);
}
What I thought I would get would be an output of:
{"laptop": "ramen"}
if I ran this
console.log(test.k.testfunc());
Let's transform into the equivalent ES5 code:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: function(){return console.log(this)}.bind(this)
}
}
Remember that this depends on how you call the function. The outer this isn't inside a function, so it will default to undefined in strict mode.
Simplified scenario below:
console.log(this) // undefined
var test = {
a: this // same `this` as above
}
You are defining the arrow function in the same scope that you defined var test. If you are defining test in the global scope, then the arrow function's context will be the global scope too.
If you are defining test inside of a method, the arrow function will share the method's context.
function method() {
const self = this;
const test = {
foo: () => console.log(self === this);
}
test.foo()
// console: true
}

How to call a function whose name is defined in a string? [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 9 years ago.
I am passing function A's or B's name in a parameter based on the situation to another function C. How can I call it in function C?
if A is defined globally, then window["A"](). However, there's no need to do that in javascript. Just pass the function itself rather than its name:
function foo() {...}
// BAD
function callFunc(someName) { window[someName]() }
callFunc("foo")
// GOOD
function callFunc(someFunc) { someFunc() }
callFunc(foo)
Like this:
window[varName]()
assuming it is in global scope
If you have
function A() {}
function B() {}
then you can do
function C(parm) {
parm();
}
if you call it with C(A) or C(B)
DEMO
You could assign the functions to properties of an object. Then in your executing function reference the property by name given the parameter passed to the function.
var myFuncs = {
a: function(){
alert("Hello");
},
b: function(){
alert("Goodbye");
}
};
function execute(name){
myFuncs[name]();
}
execute("a");
execute("b");
Working Example http://jsfiddle.net/ud6BS/

Categories