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
Related
This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 2 years ago.
the following factory function has on = false.
function Radio(mode) {
let on = false;
return {
mode: mode,
turnOn: function () {
on = true;
},
isOn: function () {
return on;
}
};
}
If I created an object using this factory function and used the function fmRadio.turnOn(); inside it to change the value of on to be true like in the following lines..
let fmRadio = Radio('fm');
fmRadio.turnOn();
The output of fmRadio.isOn(); will be on = true
So, Where does on variable change? I mean it's not part of the fmRadio object created..if we tried to call it it will return undefined
fmRadio.on;
//undefined
Does it change the value of on in the original factory function?
Variable on exists only on the scope of the function. When you are trying to access the on variable, that on variable is not exposed for usage outside the function as the function is returning only the object with mode, turnOn and turnOff. You can think of this variable (on) as its a private declard variable and it doesn't have any access from outside of the class (of course it's not like that since here you have a function, but to give you an example). If you return the on variable from the function, you will have access on that variable using ObjectName.on
what you can do is
function Radio(mode) {
let on = "test";
return {
getOn: function() {
return on;
},
setOn: function(value) {
on = value;
},
mode: mode,
turnOn: function () {
on = true;
},
isOn: function () {
return on;
}
};
}
in this case I think you can understand it better, I created two other functions, one of the functions to get the value of variable on the other one to set the value, same like getters and setters in java or c#.
now if you get the value of variable on via function getOn, the value "test" will be returned, but if you set it to another value via setOn function the variable on will be set to the new value and next time you get the updated value. This helps if you want to keep variables read only e.g
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
This question has been asked before, but all of the popular questions are 5+ years old and I'm curious to know if anything has changed since then. If you have a function that's defined somehwere
const accessParentScope = () => parentVariable;
then is there any way to access a parentVariable from the scope where the function is called? The end goal would be to do something like
function createAnotherScope() {
const parentVariable = 'some value';
return accessParentScope();
}
and have accessParentScope() have access to parentVariable without explicitly passing it as an argument.
Alternatively, is it possible to access variables from the scope of a closure? If you have a function like
function createClosure() {
const parentVariable = 'some value';
return closure = () => null;
}
then can you do something like createClosure().parentVariable? The syntax here obviously won't work, but I'm curious if anything remotely like this is possible.
Is it possible to access a variable from the caller's scope inside a function in JavaScript?
No. That would be dynamic scope. Most languages (including JavaScript) implement lexical scope. That is not going to change.
There is this, but it's rather an explicitly passed argument. The value of this is (in most cases) determined when the function is called, not when or where it is defined (arrow functions treat this differently though).
function logName() {
console.log(this.name);
}
function sayFoo() {
logName.call({name: 'foo'});
}
sayFoo();
function sayBar() {
logName.call({name: 'bar'});
}
sayBar();
As you can see, there really isn't any advantage of this over defining the function with parameters:
function logName(name) {
console.log(name);
}
function sayFoo() {
logName('foo');
}
sayFoo();
function sayBar() {
logName('bar');
}
sayBar();
As #JaromandaX said in their comment, that's what parameters are therefore, to provide values to the function at call time.
is there any way to access a parentVariable from the scope where the function is called?
No. The only way is if the context where the arrow function was declared has that attribute or variable available.
var parentVariable = 'Ele from SO'; // This is the variable available to the below arrow function (window context).
const accessParentScope = () => parentVariable; // or this.parentVariable
function createAnotherScope() {
const parentVariable = 'some value';
return accessParentScope();
}
console.log(createAnotherScope())
Alternatively, is it possible to access variables from the scope of a closure?
Yes, that way you can access the declared attributes and local variables.
function createClosure() {
this.parentVariable = 'some value'; // Note that this is an attribute (global as well) rather than a local variable.
return closure = () => this.parentVariable;
}
console.log(createClosure()());
console.log(parentVariable); // Access to global variable/attribute
Then can you do something like createClosure().parentVariable?
No, what you can do is to set an attribute to the returned function.
function createClosure() {
var closure = () => closure.parentVariable
closure.parentVariable = 'some value';
return closure;
}
console.log(createClosure()());
console.log(createClosure().parentVariable)
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
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I am adapting a controller to the "controller as" syntax.
But while transforming the code, I remarked that I can't access the "scope" variables with this out of a function.
If I understand the concept of this, then this does access the object it is used in.
As example this code:
this.scopeVariable = undefined;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
this.scopeVariable = result.foo;
});
};
So when I try to set the scopeVariable with this, I actually try to access an object from fooFunction, right?
If this is the case, how can I grab an object outside of the function within the function?
Thanks for your answers!
You have this problem because the this keyword changes definition when in a different scope. That means that if you have a simple object e.g.
var a = {
b: function() {
console.log(this); // => will log the value of "a"
setTimeout(function() {
console.log('just some rubbish');
console.log(this); // => will log inner function scope instead of "a"
}, 200)
}
}
a.b(); // to see the results
To prevent this issue from happening you can reassign this to a variable which will stay intact through deeper scopes like this:
this.scopeVariable = undefined;
var self = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
// using self. instead of this. makes the difference here
self.scopeVariable = result.foo;
});
};
Capturing the this being the scope in a variable: var that = this:
var that = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
that.scopeVariable = result.foo;
});
};