How can I get access to my y() function?
function x() {
function y() {
return 1;
}
}
Is it possible at all?
It is scoped to x, kind of like:
function x() {
var y;
}
So, yes, from within x, and no otherwise.
If you wanted it to be, you could create it as a property on x:
var x = (function () {
function x() {
…
}
function y() {
…
}
x.y = y;
return x;
})();
You mean access it from outside the function x?
That's not possible, the function y doesn't exist when x is not running. It's declared locally inside x so it's only accessible inside x.
To make it accessible outside x you need to expose a reference to it outside the function. If you expose a reference to it, it survives after the function ends. For example:
function x() {
function y() {
return 1;
}
return y;
}
// get the reference to y
var f = x();
// call y
f();
You can get access to your y function inside of the scope of the x function Only.
But you can get access to the y function if you return it from your x function or assign it to a global variable or to the variable that is in scope outside of your x function. This is also know is closure, your y function will keep the reference in memory to the scope it was created in if you pass it around.
function x() {
var anotherNum= 2;
function y() {
return 1 + anotherNum;
}
return y;
}
Now you can get the y function along with the scope it was created in. Notice that it will use anotherNum in the computation as it was created in the x function.
var yFunc = x();
console.log(yFunc()) // will print 3
One way is to return it out of the scope
function x() {
function y() {
return 1;
}
return {
y:y
};
}
Whenever you call x(), it returns an object with the function y as a member
var a = x();
a.y(); //this returns 1
This is similar to the revealing module pattern described here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FClosures
Also good to read up on closures:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FClosures
Related
When I use 'var', below function returns undefined.
var x = 3;
function func(randomize) {
if (randomize) {
var x = Math.random();
return x;
}
return x;
}
console.log(func(false)); // undefined
When I use 'let', the same function returns 3.
let x = 3;
function func(randomize) {
if (randomize) {
let x = Math.random();
return x;
}
return x;
}
console.log(func(false)); //3
How does compilation works here? Is this because of the lexical environment? I am surprised by the results. Please explain.
let is a block scope, which means if you declare let x = 3 at global scope, it would be define all thru the scope below the global scope. This is why when you call func(false) since x is in global scope, it is still defined as 3.
var is execution context scope. So when you run the function, func(false), it doesn't have context to x at the run-time of function since x wasn't defined within the function.
When I define the variable outside of a func, it returns undefined. I couldn't find out the reason why.
document.write(myFunc());
var x = 1;
function myFunc() {
return x;
}
output: undefined
However if I define variable inside the func, it works.
document.write(myFunc());
function myFunc() {
var x = 1;
return x;
}
output: 1
You have fallen foul of a common misconception. Variable and function declarations are processed before any code is executed, however assignments occur in sequence in the code. So your code is effectively:
// Function declarations are processed first
function myFunc() {
return x;
}
// Variable declarations are processed next and initialised to undefined
// if not previously declared
var x;
// Code is executed in sequence
document.write(myFunc());
// Assignment happens here (after calling myFunc)
x = 1;
When i check MDN to learn some points about closures, i faced the below function.
It can be a known pattern in javascript, but it's strange for java or .NET developer.
I want to know how it works, i know about arguments and first class object behavior in javascript language but how add5(2) assigned 2 to y variable.
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
First, any time there are named parameters - there is an implicit variable declaration. So forget the function above, just consider this
var example = function() {
var x = 5;
return function(y) {
return x + y;
}
}
var inner = example();
console.log(inner(5));
> '10'
Do you understand how the above works? if not I'd recommend looking into javascript closure and what it means.
Javascript Closures
In the above function makeAdder, the only difference is that we are passing the value of x. But x is still defined in the outer function, and the resulting returned function closes over its value
The function makeAdder returns a function, so the variables add5 and add10 are just references to functions. When you call those functions with a parameter vale, that ends up as the parameter y in the function.
You can do the same in C# for example, and the closure works the same:
public static Func<int, int> MakeAdder(int x) {
return y => x + y;
}
Using it:
Func<int, int> add5 = MakeAdder(5);
Func<int, int> add10 = MakeAdder(10);
Console.WriteLine(add5(2));
Console.WeiteLine(add10(2));
makeAdder returns a function which can be seen like:
var x = 5;
function add5(y){
return x + y;
}
makeAdder(5) called the function makeAdder, with x bound to 5. This function returns another function. Furthermore, since the value of x was provided, the anonymous function inside makeAdder knows the value of x. At this point in time, makeAdder will return:
function(y) {
return 5 + y;
}
Therefore, by assigning this new function to add5, add5 is now a function, as well. If we call add5(2), it will use the above function, and perform the following:
function(2) {
return 5 + 2;
}
Which will output 7.
How does this work?
The function defined in the closure 'remembers' the environment in
which it was created.
ref
I was just playing with JavaScript and creating constructors, and I came across this perplexing code.
var foo = function(){
this.x = 1;
return function(){
return this.x;
}
}
var x = new foo();
console.log(x);
I executed the following for this:
console.log(x); // The given output is expected for this line of code
console.log(x());
console.log(x()());
console.log(x()()());
All of the above gave me the same output as following:
function (){
return this.x;
}
Can somebody explain what is happening in the above code.
I could not give a proper title for this question. Sorry about that.
Note: I'm aware of constructors in JS. And the above code was just out of curiosity.
To make a long story short - it's not doing anything useful.
If a constructor returns an object, then the value produced by the new expression is that value rather than the constructed object. So instead of getting an instance of foo, you are getting a function that returns this.x.
It looks like this code is trying to produce a function that returns the this.x value of the created object, but that's not what it's doing. Since you are calling x() by itself, this.x is actually referring to the global x variable, so no matter how many times you call x()()(), it just returns itself.
If you used any variable name other than x and did not create an x variable (e.g. y), then y() would just return undefined, and y()() would produce a ReferenceError.
This would also fail much sooner in strict mode, becuase this inside the function would be referring to undefined when you tried to call it.
My interpretation is this:
x contains the result of calling foo().
foo() returns a function:
function(){
return this.x;
}
the body of this function is written to the console
Here is an example to the previous answer, that demonstrates it:
var x = 5;
var foo = function(){
this.x = 1;
return function(){
return this.x;
}
}
var b = new foo();
b() //--> 5
This code is all about function invocation context.
At runtime, the this referenced in this.x = 1; is bound to a different object than the this referenced in return this.x;
x() invokes the anonymous function returned by foo, in a global context. For ECMAScript 3 (and earlier) environment, global context function invocation binds the global object to this, inside the invoked function. Thus, return this.x; refers to var x you define on the global object.
In ECMAScript 5, use strict; statement can be placed in any function declaration to disable the binding of the global object in "this" way.
The anonymous, nested function can access "foo's" this in a closure:
var foo = function(){
this.x = 1;
var that = this;
return function(){
return that.x;
}
}
var x = new foo();
console.log(x); // function(){ ...
x(); // 1
Suppose I have a JavaScript function. and it contain a variable x;
function A(){
var x = 12+34;
}
Is it possible to access x from outside function x?
No, the ability to do so would not make any sense. Suppose we changed your function slightly and called it 3 times:
function x(n){
var x = n+34;
}
x(1), x(2), x(3);
At this point, the function has run 3 times, so the variable x has been created 3 times — which x would you expect to be able to access? Then there's garbage collection; how could references and data be cleared from memory if the browser had to keep variables alive once they're no longer in scope?
If you want to, you can do something like this:
function x() {
x.x = 12+34;
}
x();
or, if the variable will be static/constant as you have it
function x() { }
x.x = 12+34;
or finally, as others have pointed out, by declaring x under a different name outside of the function's scope:
var y;
function x() {
y = 12+34;
}
x();
You can not access it directly by its name, try removing 'var' from the variable declaration, as this should make the variables globals, or placing them outside the ready function. and return the value of x from the function.
You can do some thing like this:
$(document).ready(function() {
var x;
function x(){
x = 12+34;
return x;
}
alert(x());
});
Here is its jsfiddle
Hope this helps.
Yes, but not as scoped in your example above. You must use closure. Consider the following:
var x,
A = function () {
x = 12 + 34;
};
In this manner you can access x from inside the function A. What is even better is that x has direct access to the private members of A and so can be used to leak private data outside of A.