Are there any ability to get closure variables list (Ok, maybe all scope variables) in JavaScript?
Sample:
function factory(){
var _secret = "Some secret";
return function(code){
// How to get parent function variables names here?
// ...
}
}
var inside = factory();
inside();
Assuming this is for debugging purposes, you can try parsing the function body and evaluating identifiers found:
function getvars(fn, _eval) {
var words = String(fn).replace(/".*?"|'.*?'/g, '').match(/\b[_A-Za-z]\w*/g),
ret = {}
words.forEach(function(w) {
try { ret[w] = _eval(w) } catch (e) {};
});
return ret;
}
function factory() {
var _secret = "Some secret";
var _other = "Other secret";
return function(code){
var vars = getvars(factory, _ => eval(_));
return vars;
}
}
vars = factory()();
document.write('<pre>'+JSON.stringify(vars,0,3));
Needless to say, this is an extremely naive way to deal with code, so handle it with care.
One way to see them is using console.dir to get all the scopes including closures scopes and their variables list. Example:
function factory(){
var _secret = "Some secret";
var i = 0;
return function(){
i++;
return _secret + i;
}
}
var inside = factory();
inside(); // "Some secret1"
inside(); // "Some secret2"
console.dir(inside); // It shows you all variables in [[Scopes]] > Closure
Image of how you would see the console:
It works in Chromium based browsers.
Edit:
Related answer with nested scopes in related question https://stackoverflow.com/a/66896639/2391782
There's no comprehensive way to get a list of all variables in scope. You could enumerate over the this object, but that will still only give you a list of the enumerable objects on this, and even at that there will still be things like function arguments that aren't on this.
So no, this cannot be done. Also check out this similar question.
No, it isn't possible.
ECMAScript specification doesn't expose Enviroment Record objects to end user anywhere.
Since the primary concept of a closure is scope, and vars inside a closure are private, there can be no way to achieve this without exposing them somehow, like via a method.
What are you really trying to achieve?
Related
Why does the marked line fail to find protectedACMember?
var Module = (function (ns) {
function AbstractClass() {
this.protectedACMember = "abstract";
this.abstractPublicACMethod = function (input) {
this.methodToImplement();
}
}
ConcreteClass.prototype = new AbstractClass();
function ConcreteClass(){
var privateCCMember = "private CC";
var privateCCMethod = function(){
alert(this.protectedACMember); // cant find protectedACMember
}
this.methodToImplement = function(){
privateCCMethod();
console.log('Implemented method ');
}
}
ns.ConcreteClass = ConcreteClass;
return ns;
})(Module || {});
//somewhere later
var cc = new Module.ConcreteClass();
cc.abstractPublicACMethod();
are there any good patterns for simulating private, protected and public members? Static/non-static as well?
You should change that part of code like this:
var self = this;
var privateCCMethod = function(){
alert(self.protectedACMember); // this -> self
}
This way you get the reference in the closure.
The reason is, that "this" is a reserved word, and its value is set by the interpreter. Your privateCCMethod is an anonymous function, not the object property, so if you call it simply by privateCCMethod() syntax, this will be null.
If you'd like "this" to be bound to something specific you can always use .call syntax, like this:
privateCCMethod.call(this)
Another way to ensure that this means what you want is to use bind. Bind allows you to ensure a function is called with a specific value of this.
Most newer browsers support it (even IE9!) and there's a workaround for those that don't.
Bind - MDN Documentation
It fails to find protectedACMember because what the this keyword means changes when you enter the function privateCCMethod. A common practice is to store the outer this for use inside the functions:
function ConcreteClass(){
var privateCCMember = "private CC";
// store the outer this
var that = this;
var privateCCMethod = function(){
alert(that.protectedACMember);
}
...
The rest of your questions are fairly loaded and should probably be posted as a separate question.
This question is simplified version of my old question Adding scope variable to a constructor. Question is simple can I add priv variable to the fu()'s scope without changing the function? (not adding inside of the function block)
Here is fiddle
Here is the code:
fff = function() {
alert('constructed');
//alert(priv);
};
pro = {
pub: 'public'
}
var make = function(fu, pro) {
var priv = 'private';
fu.prototype = pro
return function() {
return new fu();
};
};
var cls = make(fff, pro);
var obj = cls();
alert(obj.pub);
As you can see if you de-comment the
//alert(priv);
line Uncaught ReferenceError: priv is not defined error.
I need a way to redifine the scope of the fu() function object.
I don't see the fu object listed, but I think the answer is "yes", you can add a private variable without changing the "function". Now, I may be missing something, but if I follow you, here is what you want:
var fu = {
DoStuff: function(someVar){
alert(someVar);
}
};
Then later in your code:
fu["NewPrivateVar"] = "something!";
Or in dot notation:
fu.NewPrivateVar = "someting!";
Finally:
fu.DoStuff(fu.NewPrivateVar);
Results in:
"something!"
Is that what you are looking to do?
You can't change the scope of the function by calling it from inside an object or a closure.
You can however add the variable to the scope of the function, i.e. in the global scope:
window.priv = 'private';
That will make the function work without changes, but the variable isn't very private...
I understand the concept of variable scope in the following example, but can someone explain the function-wrapping syntax (...)();, e.g. how do you use it in actually day-to-day JavaScript programming? It's not something that I know from PHP/Java/C#.
window.onload = function() {
var i = 4;
console.log(i); //4
(function showIt() {
var i = 'whatever';
console.log(i); //whatever
})();
console.log(i); //4
};
There are several ways in which this form is useful. One is to lexically scope a segment of code so that its inner variables and methods stay separate from the larger body of code that contains it. In this way, it's JavaScript's way of doing block scoping. But the most common way I use this format is as an alternative to this:
var ret = {
depth:0,
initialized:false,
helper:function() { /*help with some stuff*/ },
initialize:function(){ /*do some initialization code*/ },
action:function(){/*do the thing you want*/}
destroy:function() { /*clean up*/ }
}
The thing that absolutely kills me about this format is it is extremely time consuming to find missing braces and commas. For example, the code above won't work because the's no comma at the end of the action declaration and unless I had pointed it out, you'd have had a hard time finding the problem because when the exception is thrown, it's thrown on the entire statement, not the section that's "causing the problem". This is such a predictable problem that I simply don't use this format any more if I can possibly avoid it. I refuse. Instead, the same can be written much more clearly as:
var ret = (function(){
var self = {},
initialized = false;
var helper = function() { /*help with some stuff*/ };
self.depth = 0;
self.initialize = function() {/*do some initialization*/};
self.action = function() {/*do the thing you want*/};
self.destroy = function() { /*clean up*/ };
return self;
}());
There are two big advantages for me. One, missing braces and commas can be found more easily (when the exception is thrown, the line number will be close to the area where it's missing). And two, you can choose to keep some variables and methods private and you retain all the benefits of the first block of code.
And the last plug I'll give for this format is that the code above (which is sort of like a Singleton) can be converted into a constructor by 1) removing the invocation braces on the outside, 2) changing self = {} to self = this, and 3) optionally removing the return self at the end:
var Ret = function(){
var self = this,
initialized = false;
var helper = function() { /*help with some stuff*/ };
self.depth = 0;
self.initialize = function() {/*do some initialization*/};
self.action = function() {/*do the thing you want*/};
self.destroy = function() { /*clean up*/ };
return self; // this is ignored by the compiler if used as a constructor
};
var ret = new Ret();
This is defining a function showIT (using function showIT() {...}) similar to what you're already familiar with. The () at the end directly invokes the function in the same line as it is defined. That's probably the part that is new to you. Just like you'd say showIT() to invoke the function, you can replace the name with the actual definition and it'll work in Javascript.
JavaScript has function literals. All it's doing is making a function literal, and calling the result of the expression. Is the name what's confusing you? All a name would be used for is referring to the function inside its own body, and it's optional. (Note that that's not compatible with IE 8 and earlier.)
Unlike in C where variable names have block scope, JavaScript (like Pico) has only function scope.
So if you want to create a new name scope you can't just use { ... } as you could in C, you have to use (function() { ... })();.
I'm trying to remove the eval statement in this function. I'm used to the this[whatever] style replacement but it doesn't work out in this instance.
Have a look:
var App = (function(fw) {
var somevar1 = "hello";
var somevar2 = "world";
this.get = function(what) {
return eval(what);
}
});
var app = new App({some: "thing"});
// now for the use:
console.log(app.get("somevar1"),app);
In the function, all my normal "eval scrubbing" options are not working for instance, I cant use:
return this[what]
return [what]
return app[what]
return new Function(what);
surely this isn't an odd case where eval is necessary? .. ps I have to note that I CANNOT rescope the variables inside App as it's part of a huge codebase.
Here's something to fiddle with:
http://jsfiddle.net/xAVYa/
Unfortunately, you're out of luck; eval is the only thing that can access variables like that. Next time, don't do things that way :)
You can start a migration by keeping a data object:
var App = (function(fw) {
var data = {
somevar1: "hello",
somevar2: "world"
};
this.get = function(what) {
return data[what];
};
});
And just gradually do this across the entire codebase where you see it. It shouldn't break anything.
You cannot access an arbitrary local variable by string name without eval. So, unless you're willing to change how those variables are accessed by other code inside of the app function, you will have to stick with eval (as ugly as it seems).
If, on the other hand, you're willing to change the code inside of the app() function that accesses somevar1 and somevar2, then you have options. Note, you shouldn't have to change anything outside the app() function because you can keep the same contract for the .get() function so this isn't one of those arbitrarily hard to find all possible places everywhere in the project that might be accessing these variables. Because of the way they are currently declared, they can only be accessed directly from inside the app() function so your search/replace would be limited to that scope.
If it's OK for the variables to be properties of your object, you could do this:
var app = function(fw) {
this.somevar1 = "hello";
this.somevar2 = "world";
this.get = function(what) {
return this[what];
}
};
var app = new App({some: "thing"});
// now for the use:
console.log(app.get("somevar1"));
console.log(app.somevar1);
console.log(app["somevar1"]);
There isn’t a dynamic way to do this without eval. If the variables aren’t changing, though, you could try something like this:
var App = (function(fw) {
var somevar1 = "hello";
var somevar2 = "world";
this.get = function(what) {
switch (what) {
case "somevar1":
return somevar1;
case "somevar2":
return somevar2;
}
}
});
I'm trying to reuse a complicated function, and it would work perfectly if I could change the value of a local variable that's inside a conditional inside that function.
To boil it down:
var func = complicated_function() {
// lots of code
if (something) {
var localvar = 35;
}
// lots of code
}
I need localvar to be some other number.
Is there any way to assign localvar to something else, without actually modify anything in the function itself?
Update: The answer is yes! See my response below.
Is there any way to assign localvar to something else, without actually modify anything in the function itself?
Nope.
No, but it is possible to assign it conditionally so that the function signature (basically, the required input and output) does not change. Add a parameter and have it default to its current value:
var func = complicated_function(myLocalVar) {
// lots of code
if (something) {
// if myLocalVar has not been set, use 35.
// if it has been set, use that value
var localvar = (myLocalVar === undefined)?35:myLocalVar;
}
// lots of code
}
No.
Without changing the complicated function there is no way, in javascript you can manipilate this by using call and apply. You can override functions in the complicated function or add new if this is an option (but they won't be able to access the local variable localvar).
this is more for fun my real answer is still no.
If you are feeling crazy :)
var complicatedFunction = function() {
var i = 10;
var internalStuff = function() {
console.log(i); // 10 or 12?
};
return internalStuff();
};
var complicatedFunction;
eval("complicatedFunction = " + complicatedFunction.toString().replace(/i = 10/, 'i = 12'));
complicatedFunction(); //# => 12
If the function uses this.localvar:
var func = function() {
alert(this.localvar)
if (true) {
var localvar = 35;
}
// lots of code
alert(this.localvar)
}
var obj = {localvar: 10};
func.call(obj); // alerts 10 twice
If not, then you can't change it without changing the function.
In javascript variables are "pushed" to the top of their function. Variables in javascript have function scope, not "curly brace" scope like C, C++, Java, and C#.
This is the same code with you (the developer) manually pushing it to the top:
var func = complicated_function() {
var localvar = 0;
// lots of code
if (something) {
localvar = 35;
}
// lots of code
}
Does declaring the variable "up" one function help you out? At least the declaration is isolated.
function whatever() {
var localvar = 0;
var func = function() {
var something = true;
// lots of code
if (something) {
localvar = 35;
}
// lots of code
};
func();
alert(localvar);
}
whatever();
Here is the jsFiddle: http://jsfiddle.net/Gjjqx/
See Crockford:
http://javascript.crockford.com/code.html
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
I asked this question about three weeks ago and within a half hour got five answers that all basically told me it wasn't possible.
But I'm pleased to announce that the answer is YES, it can be done!
Here's how:
var newfunc = func.toString().replace('35', '42');
eval('newfunc = ' + newfunc);
newfunc();
Of course, it uses eval, which probably means that it's evil, or at least very inadvisable, but in this particular case, it works.