How can I access the test2() function outer either in onclick , as shown in the plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help.
<p onclick='test().test2()'> some text </p>;
<script>
//the below declaration will not change
var jQuery = 'Hi';
(function ($) {
function test(){
function test2(){
alert('text')
}
alert($)
}
console.log($);
test().test2()
})(jQuery)
</script>
You can only access test2 if you declare the function in the same scope as where you want the to access the function. In this case it means you need to declare the function in the outer scope.
You can do so by setting a variable in the outer scope like this:
var test2;
var jQuery = 'Hi';
(function ($) {
function test(){
test2 = function(){
alert('text')
}
alert($)
}
console.log($);
test(); //test needs to be called first to define test2.
test2();
})(jQuery)
I checked twice and this works:
var jQuery = 'Hi';
window.test = (function ($) {
function test(){
this.test2 = function () {
alert('text')
};
alert($);
return this;
}
console.log($);
test().test2();
return test;
})(jQuery);
Related
Why is the test fuction declaration not found in the window object? Thanks
!function(){
function test(){
console.log("testing");
}
var check = window["test"]
console.log(check); //undefined
}();
Since function test() is local to the scope of the toplevel function expression, it's not bound to window, the global scope. You can refer to it as a local variable:
!function() {
function test() {
console.log('testing')
}
console.log(test)
}()
Or bind it directly to window for a global variable:
!function() {
window.test = function test() {
console.log('testing')
}
var check = window['test']
console.log(check)
}()
You cannot access the local scope as a variable - see this question for more details.
how can I declare,set and access global variable from one function to another?
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The code above was just my sample to make it easy to understand on what I am trying to do. This is just for educational purposes. I just want to get the result in that way. Or is there a way to set a Global variable within a function and use it to another function outside that function?
What do to?
Creating variables in the Global scope is very bad practice. You shouldn't do it because it can cause conflicts especially in future JavaScript versions.
You can run the functions from a scope or object, try:
var shared = {};
$(document).ready(function () {
test1.call(shared);//undefined
test2.call(shared);
test1.call(shared);//foo
});
function test1 () {
alert(this.testvar);
}
function test2 () {
var a = 'foo';
this.testvar = a;
}
How it works
In simple terms, this will store all the variables in the object (shared). You can declared a "shared variable" by using this. instead of var. By using .call() we can choose to run the function in the scope of the object. I'm not the best at explaining, learn more here
Fiddle
Global Variables are always accessible from everywhere. But this might help you understand it better:
var testvar;
$(document).ready(function(){
console.log(testvar); // outputs: undefined
test2();
console.log(testvar); // outputs Hello World
console.log(test1()); //outputs Hello World
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return test2();
}
function test2(){
var a = "Hellow World";
testvar = a;
}
console.log(testvar);
test2() is not called. It needs to be called in order to redeclare the variable
https://jsfiddle.net/uwzapwrk/
I use this method and it works for me
function somefunctionname(){
// Some action
anotherfunctionname(put_your_value);
}
function anotherfunctionname(put_parameter_as_you_want){
var some_var = put_parameter_as_you_want;
// Some action with your var
}
This method work after somefunctionname() was execute and you can execute the anotherfunctionname() with variable was store on somefunctionname()
Is there a more elegant way of writing something like this, where myFunction is asigned to the function func but func is also executed during the assignment?
var myFunction = (function(){
var func = function(){
console.log('hello world');
};
func();
return func;
})();
...
myFunction();
var myFunction = (function func(){
console.log('hello world');
return func;
})();
You can name your anonymous function. This name will only be accessible inside of the function itself, though.
Your core statement is this
var <name> = (<functionExpression>)();
I don't see how this could be more elegant.
Assignments expressions return the assigned value, but you have to declare the variable separately so you still have to repeat the identifier:
var outer;
(outer = function() {
var inner;
return (inner = function() {
print('hello world');
})(), inner;
})();
outer();
That said if I saw this code from a coworker I'd whap him with a rolled up newspaper.
I'm using jQuery and have a function wrapped inside an immediately-invoked function expression like so:
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
(function ($) {
var message = 'x called';
function x() {
alert(message);
}
})(jQuery);
x();
</script>
This will result is an error since the function "x" is not defined outside the immediately-invoked function expression. Is there any way to call the function "x" outside the immediately-invoked function expression?
Only if you expose the function in some way. For example, you can return it from the outer function:
var x = (function ($) {
var message = 'x called';
function x() {
alert(message);
}
return x;
})(jQuery);
x();
Or, similarly, you can return it on an object:
var obj = (function ($) {
var message = 'x called';
function x() {
alert(message);
}
return {"x": x};
})(jQuery);
obj.x();
Functions and variables declared inside of a function are not directly reachable from outside of that function, unless you provide some means of accessing them by returning something, or giving a reference to a variable declared outside of that function.
Make a namespace for other classes or functions you might want to do this with. You don't want to continually pollute the global namespace but there's no reason you can't make one namespace that's global and put your individual things underneath that:
(function($){
window.MyNamespace = function(){};
var message = "Something here";
$.extend(MyNamespace, {
x: function(){
alert(message);
}
});
})(jQuery)
MyNamespace.x()
You can change your code as follows:
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
var x;
(function ($) {
var message = 'x called';
x = function () {
alert(message);
}
})(jQuery);
x();
</script>
jsFiddle link for this: http://jsfiddle.net/aLnbn/
Yes, ( one way is to: )just return it from the IIFE using a return statement, also you need to "catch" the return by assigning a variable to the IIFE
var foo = (function(){
return your_function;
}());
You can access your method by using your IIFE to return (or augment) a global variable.
You might do it like this:
var globalObject = (function (theObject, $) {
if (theObject.theMethod) {
return theObject;
}
var message = 'theMethod called';
theObject.theMethod = function () {
alert(message);
};
return theObject;
})(globalObject || {}, jQuery);
globalObject.theMethod();
The pattern we use is slightly better.
We have one global object (ie namespace) and we add modules to it by importing js files that contain IIFE's.
Each IIFE adds a new module to a single global object.
This makes it so our entire project has only one global object that can optionally utilize any of our modules by including a file.
I recommend checking out this article, which is a good discussion on the JavaScript module pattern:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Try this:
var miFunc = (function($) {
var message = 'x called';
function x() {
console.log(message);
}
this.x = x;
return this;
})(jQuery);
miFunc.x();
Test: http://jsbin.com/erucix/2/edit
One of the purposes of a closure is to limit scope. That is why x() is defined and can be called inside of your immediately-invoked function expression but is undefined outside.
To have your code work without refactoring, you can take advantage of JS grammar which differentiates between a function statement and a function operator. Both are semantically identical but the latter can be assigned to a variable which works just right for your scenario:
var x; //scoped *outside* of the closure
(function ($) {
var message = 'x called';
x = function() {
alert(message);
}
})(jQuery);
x(); //alerts 'x called'
You can access your method by using your IIFE to return a global variable.
//IIFEs - Immediately Invoked Function Expressions
var namespaceTestIIFE = (function ($) {
/** Public functions and state. */
var pub = {};
$(document).ready(function () {
//your on ready logic
});
pub.testAlert = function () {
alert('Hello TestAlert');
}
return pub;
})(jQuery);
OR
var compareForm = (function ()
{
/** Public functions and state. */
var pub = {};
pub.testAlert = function () {
alert('Hello TestAlert');
}
return pub;
}());
To access function use "namespace.functionname" for example -
namespaceTestIIFE.testAlert();
I'd like to call functions I've defined within the document ready function of jQuery, but am having a bit of trouble. I have the following code:
jQuery(document).ready( function($) {
function test1() {
alert('test1');
}
function test2() {
alert('test2');
}
var test_call = '2';
var fn = 'test' + test_call;
// use fn to call test2
});
I don't want to use eval, and window[fn] doesn't seem to be working. The two test functions don't appear to be indices in the window variable. I appreciate the help and knowledge.
All I can think of that doesn't use eval() or some form of eval (passing a string to setTimeout() is a form of eval()), is to register the relevant function names on an object and then look up the function name on that object:
jQuery(document).ready( function($) {
function test1() {
alert('test1');
}
function test2() {
alert('test2');
}
// register functions on an object
var funcList = {};
funcList["test1"] = test1;
funcList["test2"] = test2;
var test_call = '2';
var fn = 'test' + test_call;
if (fn in funcList) {
funcList[fn]();
}
});
or the registration could be done in the definition of the functions. If they were global functions, they would be implicitly registered on the window object, but these are not global as they are scoped inside the document.ready handler function:
jQuery(document).ready( function($) {
var funcList = {};
funcList.test1 = function test1() {
alert('test1');
}
funcList.test2 = function test2() {
alert('test2');
}
var test_call = '2';
var fn = 'test' + test_call;
if (fn in funcList) {
funcList[fn]();
}
});
Or, you could move the functions to the global scope so they are automatically registered with the window object like this:
function test1() {
alert('test1');
}
function test2() {
alert('test2');
}
jQuery(document).ready( function($) {
var test_call = '2';
var fn = 'test' + test_call;
if (fn in window) {
window[fn]();
}
});
The best way, if not Eval, would be to use setTimeout with zero milliseconds, as you can specify the function as a string.
setTimeout('myfunction()',0,);