Access Variable from a different function without creating global variables - javascript

I've recently started using CasperJS to do web automation, and something is confusing me a little.
How do access local variables from one function to another? For example:
casper.start('http://google.com', function(){
var someVar = 20;
});
casper.thenOpen('http://google.com/analytics', function(){
// How can I access someVar?jav
});
I know someVar is not in scope in the second function, but how do I access someVar in the second function without defining globals?

What about using an object to get a certain variable as property:
var myObj = {};
casper.start('http://google.com', function(){
myObj.someVar = 20;
});
casper.thenOpen('http://google.com/analytics', function(){
console.log(myObj.someVar);
});

Without using Globals you say, then create a third function (bean) which would have var someVar = 20; local variable and provide getter and setter functions to use by others.
var SharedSpace = (function(){
var shared = 20; //initialization
return {
getShared: function(){
return shared;
},
setShared: function(val){
shared = val;
}
}
})();
(function(){
alert(SharedSpace.getShared());
SharedSpace.setShared(500)
})();
(function(){
alert(SharedSpace.getShared());
SharedSpace.setShared(400)
})();
(function(){
alert(SharedSpace.getShared());
SharedSpace.setShared(10)
})();

You can't do this so that it is clean and makes sense. Defining a global variable is the only clean way. You could of course put the variable on the casper object, but that is not clean as it might interfere with the CasperJS functionality if you use wrong variable names. I only do this when I define helper functions for casper.
casper.start('http://google.com', function(){
this.someVar = 20;
});
casper.thenOpen('http://google.com/analytics', function(){
this.echo(this.someVar);
});

Related

Global import variables and IIFEs

A number of different articles around the web have been professing the greatness of using global import when designing modules (similiar to jQuery).
So, doing something like this...
(function(globalVariable){
globalVariable.printStuff = function(){
console.log(‘Hello World’)
};
}(globalVariable));
...means that I can call a function with something like this:
globalVariable.printStuff();
The problem is, whenever I run this in the console, I keep getting:
globalVariable undefined
My quesiton is, where exactly do I need to declare this variable so that I can get this to work?
For such a real simple module, you don't need any IIFE. Just write an object literal:
var globalVariable = {
printStuff: function() {
console.log('Hello World');
}
};
globalVariable.printStuff();
If you want to use an IIFE scope, you still have to create the object somewhere. That could be inside the module or outside:
var globalVariable = (function() {
var module = {};
var localVariable = 'Hello World';
module.printStuff = function() {
console.log(localVariable);
};
return module;
}());
globalVariable.printStuff();
var globalVariable = {};
(function(module) {
var localVariable = 'Hello World';
module.printStuff = function() {
console.log(localVariable);
};
}(globalVariable));
globalVariable.printStuff();
For a browser window object is the object that stores all the global variables. Below code shows a basic implementation of IIFEs with global variable.
//Set a variable 'globalVariable' in the window object
window.globalVariable = 10;
//Access the global variable 'globalVariable' in IIFE
(function(globalVariable) {
console.log(globalVariable);
})(globalVariable);

How to make the object as public without removing var in javascript

(function(){
var a = {};
a.b = function(){
alert('this is b');
}
}());
How to make the 'a' object as public in above code without removing 'var', means 'a' can access even from another file like below.
(function(){
a.b();
}());
Note: Dont say to remove 'var', i know that way. But i want to is their any other way that without removing 'var'.
You can attach it to the global scope. In web browsers, this is the window object.
window.a = {};
Later on, you can reference it by window.a or just a.
This is generally discouraged though as collisions can occur when two unassuming scripts run and define the same thing. It would be much better to wrap whatever you need in closures.
You can return a from the IIFE:
var a = (function(){
var a = {};
a.b = function(){
alert('this is b');
}
return a;
}());
or create a property to window:
(function(){
var a = {};
a.b = function(){
alert('this is b');
}
window.a = a;
}());

this opreator for nested functions

Sorry if my question is silly one,I searched on google but I could't find anything useful.
Here I have module with 2 functions inside it and here is the code
var sample = (function(){
var _return = [];
_return.bar = function(){
alert("hello world");
};
_return.foo = function(){
function test(){
this.bar();
};
};
return _return;
})();
sample.foo();
And my questions:
How can I access to the bar function inside test function? I tried this.this.bar() or parent.this.bar() but none of them worked.
And how can I access it with this operator?
Usually (unless one has used bind to change the context of a function), the this context is bound to the object on which the function is being called, i.e., if you call foo.bar(), then inside bar, this === foo. In your case, since you are returning _return, you want to access the function bar which is defined on the same object, i.e. this.bar. However, since you will call test directly, this will be bound to the window object.
There are three main ways of working around this issue:
Save the context while you can
_return.foo = function(){
var self = this;
function test(){
self.bar();
};
};
Working demo: http://jsfiddle.net/jcovmspr/
Use bind
The other approach is using bind (ES5):
_return.foo = function(){
function test_(){
this.bar();
};
var test = test_.bind(this);
};
Use arrow syntax
The third approach is using arrow syntax for defining test but this is ES6 only and you will need a transpiler to support more common browsers:
_return.foo = function(){
var test = () => {
this.bar();
};
};
You can use a closure like below,
Note: I prefer using 'that' or 'me' rather than 'self' because self is a special keyword in JS.
_return.foo = function() {
var that = this;
function test(){
that.bar();
}
};
or you can use bind:
_return.foo = function() {
var test = (function () {
this.bar();
}).bind(this);
};
Just refer to _return instead of this:
var sample = (function(){
var _return = {
bar: function(){
alert("hello world");
},
foo: function(){
return function test(){
_return.bar();
};
}
};
return _return;
})();
sample.foo()();
(Also, I've used a proper object literal instead of creating properties on an array)

How to access properties of object created and returned from a function

var steve = function() {
var bob = {};
bob.WayCoolTest = function () {console.log('done deal');};
return bob;
}
window["steve"]["WayCoolTest"]
running this in chrome console, my test app, anywhere results with undefined. I do not understand why, can someone explain why this does not work and help me fix it. Thank you very much!!
Using window is usually redundant - let me demonstrate:
var foo = '123';
alert(foo); //123
alert(window.foo) //123
alert(window['foo']) //123
It is evident which is more convenient. There is a circumstance in which the use of window makes sense, but that circumstance is almost always because of poor architecture. Using window allows us to access a variable global variable - funny wording :) This should clear it up:
var foo = '123';
var bar = 'abc';
var prop;
if (blah) { //some condition here
prop = 'foo';
}
else {
prop = 'bar';
}
Now...how can we use prop to get the value of a corresponding variable?
console.log(window[prop]); //123 or abc - bracket notation lets us use variable property names
This sort of thing is very common within objects, but not with window. The reason is that we should be avoiding global variables (properties of window) as much as possible. Therefore, any logic that needs a variable property name should be inside of an object, dealing with objects - NOT window. Now window can be out of the picture.
It is usually bad practice to create functions inside of other functions. That would mean that each time you call function A, you recreate function B. Most of the time, people do that because they don't know better, not because they need to.
It appears to me that you intended to give steve a property called WayCoolTest, both being functions. That can be done.
var steve = function() {
console.log("I'm Steve!");
}
steve.WayCoolTest = function() {
console.log("I'm a Way Cool Test!");
}
steve(); //I'm Steve!
steve.WayCoolTest(); //I'm a Way Cool Test!
This works because functions are objects in javascript. Therefore, you can add properties to them.
Let's step it up!
To emphasize good practices, I'm going to wrap this example in an object testApp (it acts like a namespace..we're using that instead of window).
I will create a property of testApp called steve, which will be a function.
Rather than creating steve directly as a function, I will use an IIFE (immediately invoked function expression), which is a function that will return something to be set as steve.
Inside the IIFE, I will create the function for steve and also attach WayCoolTest to it, as demonstrated in the previous example, then that function is returned and assigned to steve.
var testApp = {
steve : (function() {
var steve = function() { //the name here doesn't matter, just being consistent, since this will be the value of the property `steve`.
console.log("I'm Steve!");
}
steve.WayCoolTest = function() {
console.log("I'm a Way Cool Test!");
}
return steve;
}());
};
testApp.steve(); //I'm Steve;
testApp.steve.WayCoolTest(); //I'm a Way Cool Test!
Now, let's consider another variation.
var testApp = {
steve : (function() {
var steve = function() { //the name here doesn't matter, just being consistent, since this will be the value of the property `steve`.
console.log("I'm Steve!");
WayCoolTest(); //Steve can use this, but nothing else can! Encapsulation.
}
var WayCoolTest = function() { //THIS PART!! No longer a property of "steve"
console.log("I'm a Way Cool Test!");
}
return steve;
}());
};
testApp.steve(); //I'm Steve! I'm a Way Cool Test
testApp.steve.WayCoolTest(); //undefined, of course
That is very useful if for example steve is a complicated function and you want to break it up into some other small functions that only steve will know about.
To complement the other answers, your code would work this way:
var steve = function() {
var bob = {};
bob.WayCoolTest = function () {console.log('done deal');};
return bob;
}
window["steve"]()["WayCoolTest"]();
or
var steve = (function() {
var bob = {};
bob.WayCoolTest = function () {console.log('done deal');};
return bob;
})();
window["steve"]["WayCoolTest"]();
or, the dirtiest way...
steve=(function() {
var bob = {};
bob.__defineGetter__("WayCoolTest", function () {console.log('done deal');});
return bob;
})();
window["steve"]["WayCoolTest"];
Assuming steve is in the global scope and you dont seem to use steve as a constructor you can use immediate function and return the new object that you have created inside of it.
var steve = (function () {
var bob = {};
bob.WayCoolTest = function () {
console.log('done deal');
};
return bob;
})();
window["steve"]["WayCoolTest"]();
If it is in a closure then you would have to either remove var for hoisting to happen so it becomes a part of window or set it to the window object as a property.
window.steve = (function () {
var bob = {};
bob.WayCoolTest = function () {
console.log('done deal');
};
return bob;
})();
If you declare using var it doesn't get associated with the global window scope. It's instead a local variable. Also bob is not a property on the steve object they way you have it set up

How to cache/precalculate something(without global variable)?

What I want to do is to sending data between two handlers.
element.onmousedown = function() {
data = precalculate();
}
element.onmouseup = function() {
dosomething(data);
}
if the data is a global variable it works. People says global variable is evil. But I don't know how to do without it.
or I misunderstood "global variable"?
Just scope the variable if you don't want/need it to be global:
(function() {
var data;
element.onmousedown = function() {
data = precalculate();
}
element.onmouseup = function() {
dosomething(data);
}
})();
EDIT: To clarify, the only way to create a new variable scope in javascript is in a function.
Any variable declared with var inside a function is inaccessible to the outer scope.
In the code above, I created an IIFE (immediately invoked function expression), which is simply a function that is invoked as soon as it is created, and I placed your data variable (along with the handler assignments) inside of it.
Because the handlers were created in a scope that has access to the data variable, they retain their access to that variable.
To give another example:
var a = "a"; // global variable
(function() {
var b = "b"; // new variable in this scope
(function() {
var c = "c"; // new variable in this scope
// in this function, you have access to 'a', 'b' and 'c'
})();
// in this function you have access to 'a' and 'b' variables, but not 'c'
})();
// globally, you have access to the 'a' variable, but not 'b' or 'c'
In this case a global variable would make sense. Another possibility is to attach the value to the DOM element:
element.onmousedown = function() {
// 'this' should point to the element being mouse downed
this.data = precalculate();
};
element.onmouseup = function() {
// 'this' should point to the element being mouse upped
var data = this.data;
dosomething(data);
};
You misunderstood "global variable is evil".
In fact, what really happened is that someone wanted to be "part of the crowd", and so told you a sweeping generalisation, when in fact they should have said "only use global variables where appropriate".
Well, they are appropriate here, my friend.
JQuery makes this possible by using the .data() function:
http://api.jquery.com/jQuery.data/
You can get away with using global variables as long as you keep them to a minimum, for example you can place stuff in a single global namespace:
App = {};
element.onmousedown = function() {
App.data = "hello";
}
element.onmouseup = function() {
console.log(App.data);
}
Another more general solution is to create functions that cache their results using a technique that is called memoization. There's plenty of stuff if you search.
The following code does exactly that :
Function.prototype.memoize = function() {
var fn = this;
this.memory = {};
return function() {
var args = Array.prototype.slice.call(arguments);
return fn.memory[args] ? fn.memory[args] : fn.memory[args] = fn.apply(this, arguments);
};
};
e.g. You have an expensive function called exfunc..
newFunc = exfunc.memoize();
The above statement creates a new function called newFunc that caches the result of the original function so that the first time the actual code is being executed and all subsequent calls are retrieved from a local cache.
This mostly works with functions whose return value does not depend on global state.
More info :
http://osteele.com/archives/2006/04/javascript-memoization

Categories