how I can access the global variable and not the parameter value? - javascript

I want to access the variable with the "apfala"
var frucht="apfala";
function getFrucht(frucht){
console.log(frucht);
console.log(this.frucht) // I want here the apfala one, I thought .this would work
}
getFrucht("apfel");
Or do I have to rename them differently?

http://eslint.org/docs/rules/no-shadow
Shadowing is the process by which a local variable shares the same
name as a variable in its containing scope. For example:
var a = 3;
function b() {
var a = 10;
}
In this case, the variable a inside of b() is shadowing the variable a
in the global scope. This can cause confusion while reading the code
and it’s impossible to access the global variable.
Your code suggests that you need to rethink whatever it is you are trying to do. As it is unclear as to the true nature of what you are trying to do, it is hard to suggest an alternative solution to your problem (other than do not shadow or use globals), if you have one rather than just curiosity?
Please don't do this, but this should work in all environments.
'use strict';
var getGlobal = Function('return this');
getGlobal().frucht = 'apfala';
function getFrucht(frucht) {
console.log(frucht);
console.log(getGlobal().frucht); // I want here the apfala one, I thought .this would work
}
getFrucht('apfe');
Also see: https://www.npmjs.com/package/system.global

In case your javascript runs in a browser, you can use the window global variable in order to access the variable frucht that defined in the global scope:
var frucht="apfala";
function getFrucht(frucht){
console.log(frucht);
console.log(window.frucht) // I want here the apfala one, I thought .this would work
}
getFrucht("apfel");

If it is a global and you are running in a browser:
You can use window.frucht as global variables are properties of the window object.
Not reusing the same variable name would be a much better idea though. It avoids the dependency on globals and the confusing of reusing names.

Generally speaking, in JavaScript, if you want to pass a parent scope to a child one, you need to assign this in the parent to a variable and access that variable inside the child:
var frucht="apfala";
var parent = this;
function getFrucht(frucht){
console.log(frucht);
console.log(parent.frucht);
}
getFrucht("apfel");
Also, as stated in other answers, if you are working in a browser, just use the window object to attach and access global variables (window.frucht="apfala", then use window.frucht to access that variable)
Hope that helps.

Related

JavaScript: Accessing variable/property of middle/outer functions in nested functions

I'm learning Javascript, and had this question. Here's some sample code:
var xq = false;
var fooyy = function ttt() {
var xq = false;
baryy = function() {
var xq = true;
console.log(xq);
console.log(ttt);
console.log(fooyy);
console.log(ttt.xq);
console.log(fooyy.xq);
console.log(window.xq);
}();
};
fooyy();
console.log(xq);
console.log(fooyy.xq);
Looking at the output, my question is, so does it mean that from an inner nested function, properties and variables of outer functions can't be accessed (both in the cases of having the same name and otherwise)? Or if they can, could you explain how and why? (I see that the local and global variables are accessible) Thanks!
does it mean that from an inner nested function, properties and variables of outer functions can't be accessed?
No. Those are not properties, they are variables. You tried to access them as properties of the functions, which don't exist.
I see that the local and global variables are accessible. What about variables of outer functions (both in the cases of having the same name and otherwise)?
They can be accessed as long as they have different names. This is known as lexical scope, and works even after the outer function has returned - the inner one will form a closure. You can access them simply by their name, they are local variables.
If you do however have a variable of the same name in your local scope, like in your example the variable xq, that local variable will shadow the variable from the outer scope and make it inaccessible. If you want to access it, you need to rename either variable.
What you have there is a closure, nicely explained in this SO question.
Also, please have a look at this SO question, where people invested lots of effort to explain what a closure is.
In short, baryy function has access to outer variables.

Angular - Should I use local variable or this.variable

I was looking for this but could not find a question as simple as I want it. The problem is really simple: In angular js, should I use local variables, or properties of this (in cases when I don't need to use this).
Example:
// I need "this" here because I need this collection in template
this.collection = SomeService.fetchCollection();
// I can use either "foo" or "this.foo" here, which one is better?
this.fetchSomeData = function(type) {
var foo = AnotherService.foo(type);
return FooService.call(foo);
}
A local variable, so it can be cleaned up as soon as the method exits. Otherwise it would stay unused in the parent's namespace.
But in 99% of cases that will have no real-world effect, so it doesn't matter.
Because you haven't declared 'foo' as a var it will be a global here, which is bad. You should at least prefix it with 'var' so it's scoped to the function and not globally; it shouldn't be available outside the function.
in my opinion it is a good practice not to reveal everything and keep it encapsulated - for example, it avoids moving logic to view which is bad
also, consider that you have a for loop iteration over i variable - would you also use this.i for such purpose?

Get the current scope of a Javascript Function [duplicate]

When I call a function, a local scope is erected for that call. Is there any way to directly reference that scope as an object? Just like window is a reference for the global scope object.
Example:
function test(foo){
var bar=1
//Now, can I access the object containing foo, bar, arguments and anything
//else within the local scope like this:
magicIdentifier.bar
}
Alternately, does anyone have a complete list of what is in the local scope on top of custom variables?
Background: I'm trying to get down to a way of completely shifting to global scope from within a function call, the with statement is a joke, call works a little better, but it still breaks for anything declared in function scope but not in global scope, therefore I would declare these few cases in global scope, but that requires me to know what they are. The IE function execScript makes a complete shift, but that only solves the problem for IE.
Note: To anyone loading JavaScript dynamically, setTimeout(code,1) is a simple effective hack to achieve global scope, but it will not execute immediately.
No, there's no way to reference the variable object of the execution context of a function binding object of the variable environment of the execution context (that's what that thing is called [now; hence the strikethrough]; details in §10.3 of the specification). You can only access the limited view to it you get with arguments (which is very limited indeed).
Usually when I've wanted to do this, I've just put everything I wanted on an object and then used that (e.g., passed it into a function). Of course, any functions created within the context have access to everything in scope where they're created, as they "close over" the context; more: Closures are not complicated.
I know this is hugely late, and you're probably not even slightly interested any more, but I was interested in the feasibility of this too and you should be able to make a work around of some sort using:
(function(global) {
var testVar = 1;
global.scope = function(s) {
return eval(s);
}
})(this);
then running:
scope('testVar'); // 1
returns the variable from within the closure. Not particularly nice, but theoretically possible to wrap that in an object, perhaps using some validation and getters and setters if you needed?
Edit: Having re-read the question, I assume you'd want to access it without having to specify a function in the scope itself, so this probably isn't applicable. I'll leave this here anyway.
Certain versions of Netscape had a magic property in the arguments object that did what you're looking for. (I can't remember what it was called)
What about something like this?
<script type="text/javascript">
var test = {
bar : 1,
foo : function () {
alert(this.bar);
}
}
test.foo();
</script>
You don't need a keyword to reference a variable in the local scope, because it's the scope you're in.

Reading a variable value inside a named function in javascript

This may be very simple but i lost my way in finding the answer,
I have a named function inside a Backbone view. I'm trying to write unit test for this named function and i could see a variable is being declared in function scope. The state of this variable changes based on certain scenarios.
I have instantiated the view object inside my test suite and when i do a console.log(viewObject.namedFunction) i see the entire function being logged properly. Now how do i access the variable inside the namedFunction, i was expecting something like viewObject.namedFunction.variableName but it will not work and when i did that, it was not working as expected.
If the variable is tied to viewObject scope then it would have been easy to access it. But in this scenario it is not so can some one please help me in getting a hold on the variable inside named function in view object from test suite.
I think I understand your confusion, because when you define a variable using var in the window scope, it becomes a property on the window object... It would seem to follow that when you define a variable in a child scope, it should become a member of the local context, right? Nope. Globals are special ;-)
In fact, if that were the case, there would be no privacy!
If you want sign to be public, be explicit.
obj = {
namedFunction : function myself() {
console.log(myself);
myself.sign = 23;
}
};
obj.namedFunction.sign;
The only problem with this approach is that you can now assign a new value to sign from anywhere. The classic and preferred approach to this problem is to create a getter function for your private variable.
var obj = {
namedFunction : function myself() {
var sign = 3;
myself.getSign = function(){return sign;};
}
};
obj.namedFunction.getSign();
This isn't by any means the only approach, but I hope it was helpful.
One way to do this is like such:
namedFunction = (function(){
var theActualFunction = function(){
//Do something
//Access variable like: theActualFunction.MyVariable
};
theActualFunction.MyVariable = "value";
return theActualFunction;
}());

JavaScript: Reference a functions local scope as an object

When I call a function, a local scope is erected for that call. Is there any way to directly reference that scope as an object? Just like window is a reference for the global scope object.
Example:
function test(foo){
var bar=1
//Now, can I access the object containing foo, bar, arguments and anything
//else within the local scope like this:
magicIdentifier.bar
}
Alternately, does anyone have a complete list of what is in the local scope on top of custom variables?
Background: I'm trying to get down to a way of completely shifting to global scope from within a function call, the with statement is a joke, call works a little better, but it still breaks for anything declared in function scope but not in global scope, therefore I would declare these few cases in global scope, but that requires me to know what they are. The IE function execScript makes a complete shift, but that only solves the problem for IE.
Note: To anyone loading JavaScript dynamically, setTimeout(code,1) is a simple effective hack to achieve global scope, but it will not execute immediately.
No, there's no way to reference the variable object of the execution context of a function binding object of the variable environment of the execution context (that's what that thing is called [now; hence the strikethrough]; details in §10.3 of the specification). You can only access the limited view to it you get with arguments (which is very limited indeed).
Usually when I've wanted to do this, I've just put everything I wanted on an object and then used that (e.g., passed it into a function). Of course, any functions created within the context have access to everything in scope where they're created, as they "close over" the context; more: Closures are not complicated.
I know this is hugely late, and you're probably not even slightly interested any more, but I was interested in the feasibility of this too and you should be able to make a work around of some sort using:
(function(global) {
var testVar = 1;
global.scope = function(s) {
return eval(s);
}
})(this);
then running:
scope('testVar'); // 1
returns the variable from within the closure. Not particularly nice, but theoretically possible to wrap that in an object, perhaps using some validation and getters and setters if you needed?
Edit: Having re-read the question, I assume you'd want to access it without having to specify a function in the scope itself, so this probably isn't applicable. I'll leave this here anyway.
Certain versions of Netscape had a magic property in the arguments object that did what you're looking for. (I can't remember what it was called)
What about something like this?
<script type="text/javascript">
var test = {
bar : 1,
foo : function () {
alert(this.bar);
}
}
test.foo();
</script>
You don't need a keyword to reference a variable in the local scope, because it's the scope you're in.

Categories