Self invoking functions javascript - javascript

I wrote a self invoking function in both firefox and chrome it it wouldn't invoke.
I wrote something to the effect of
(function () { alert("THE"); })();
do self invoking functions not work in current browsers?
I did include all essential tags and all other code works on the page

"Self-invoking functions" are not really a part of javascript, it's just a term that people are calling a specific pattern of code (like AJAX, etc.); these patterns should work anywhere that javascript works.
What you're calling a "self-invoking function" is just creating an anonymous function and immediately calling it (as opposed to say storing it in a var, as an object value, as a function param, etc.).
That is, the following are basically the same:
var f = function(){...}; f()
and
( function(){...} )()
So because your 'self-invoking function' is a basic part of javascript, there is no possible way it's not working unless the insides aren't working or your environment is messed up. You could copy-paste your code onto a new blank page, and it would work fine. Something else must be going wrong:
Check your errors in your dev console. Specifically, check to make sure you don't have a syntax error or that there isn't some weird thing going on with the webpage you're testing it on (e.g. if you somehow redefine alert...).

I had this issue with a self invoking function which produced this error...
Uncaught TypeError: object is not a function
The problem was caused by not having a semi colon ending the line before the opening bracket

That function works. Javascript supports functional programming, so for a browser not to run that code, even for a very old browser that would be absurd. Are you sure that statement is being reached? Try debugging javascript that occurs before that statement.

<script type="text/javascript">
(function() {
alert('Hello World!');
})();
</script>
Works in every browser I have installed on this machine.

This function definitely works. I would check your browser's console for any js errors in your page. Perhaps you could try to put a simple console.log function at the beginning of your script to see if any JavaScript is being called in the first place.

This self invoking function with return value will work in all current browsers(Safari, Chrome and Firefox) without issue. This function executes immediately, automatically and anonymously.
<script type="text/javascript">
alert((function(){
return("Hello World");
})());
</script>

I had a similar problem. I'm mentioning it below.
I couldn't run this self-invoking function on any browser
(function myfunc() {
var x = 34;
console.log(x);
})();
but whenever I added window.onload like below, it worked fine:
window.onload = (function myfunc() {
var x = 34;
console.log(x);
})();

Related

Cannot Find JavaScript Namespace

I am trying to create namespaces in JavaScript as in the following script:
var hlAdmin = hlAdmin || {};
hlAdmin.editCompany = function (src) {
// function script
}
Then I call the function in HTML:
onclick="hlAdmin.editCompany(123)"
I get a reference error: Cannot find "editCompany".
Anyone know why?
Based on your comments I assume the following:
The equivalent script (and scoping is like):
<html><head>
</script>
var hlAdmin = hlAdmin || {};
hlAdmin.editCompany = function (src) {
// error in this script
}
</script>
</head></body>
<button onclick="hlAdmin.editCompany(123)">Caption</button>
</body></html>
In this example hlAdmin is indeed in the global scope (the root-scope of the host, called window in browsers).
If (in this example) you get reference error: Cannot find "editCompany", then one should look at other error-messages in your (browser's) error-log, because when there is a fatal error in the function for hlAdmin.editCompany, then that function will not be created (hence .editCompany becomes a property that points to undefined instead of a method that points to the function OR .editCompany doesn't even exist (depending on engine/error)).
To investigate if you indeed have a scoping-problem you could test this by: window['hlAdmin'] || (window['hlAdmin']={}); (or some equivalent variant). If that made the code work, then it seems you have some scoping-problem.
Hope these steps help someone in the future.
It's generally considered bad form to mix inline javascript and non-inline. The preferred way to do this would be to keep all the javascript in one place using an event handler:
window.hlAdmin = window.hlAdmin || {};
window.hlAdmin.editCompany = function (src) {
// function script
}
document.getElementById('yourElementId').onclick = function() {
hlAdmin.editCompany(123);
};
To more specifically address the issue: One thing that could cause this issue is if the hlAdmin object is not ending up in the global scope. You stated that this declaration is "at the top of the JavaScript file", but if it's in any kind of function (such as a function set to window.onload, or the jQuery $(function() { ... });) it would not end up in the global scope when declared as a var. A variable declared with var will only end up globally scoped if it's in the root scope, outside of any kind of function. If rather than using var hlAdmin you instead use window.hlAdmin, this will make sure that even if you're inside a document ready function or something similar, you're creating your hlAdmin in the global context, which will fix the problem if it is in fact an issue of scope.
I found the problem.
The browsers (at least Aurora and Chrome) are dropping the namespace in the onclick attribute. When you look at the browser html the namespace has just disappeared from the markup.

Anonymous JavaScript function not executing

I could really use a second pair of eyes on this. I get the following error:
"Uncaught TypeError: undefined is not a function"
Can anyone see what is wrong with this function because I can't seem to debug
$(function(){
$('#div-id').insertBefore('#sumbit-button');
})();
jQuery already executes the function you pass to it, it does not return a function so you can't call it.
$(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
});
There's 2 different things you can mean with this code. Either you're trying to make a function run on DOM ready, which would use the jQuery code:
$(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
});
Which is also what aduch said, but you can also be referring to a self-executing anonymous function, which would be this vanilla JS code:
(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
})();
The difference is that the first code requires jQuery to be included on the page, and loads the code when the DOM is ready. The second code runs the code immediately, but uses the anonymous function to change the scope of the variables. You're probably trying to do the first thing, but I thought I'd let you know about the second one too.

anonymous functions javascript, how to access source code?

I got some JS Code that gets inside a random Anonymous js function.
I want that code (for example alert('hello') ) to dump/alert
the entire script block/object which it was injected into.
kinda like document.body.innerHTML but for the anonymous function block
result should be like :
Function()({ somecode; MyAlert(...) } )()
or
Try { some code; mycode; } catch(e) { }
Mind your terms. "(browser) script block" literally means script element's code by the spec.
Use "javascript block" or "javascript object" to mean a block or an object.
Do not create confusing new terms; do read and research.
Blocks are not objects; they are language statements.
Just like you cannot "get the code/variables of current line", you cannot "get the code/variables of current block", try block or not.
Stepping back, for now you can use Function.caller to get the function calling your code:
var mycode = function me(){ if ( me.caller ) alert( me.caller.toString() ); };
(function(){ var some = 'code'; mycode(); })();
// Alert "function(){ var some = 'code'; mycode(); }", even when it is anonymous
Note that you get the whole function's code, not the function block's code which excludes parameters and function name.
Function.caller may be removed in future, like arguments.caller. (Both are troubles. What if a cross origin function on the call stack contains private api key code? How should js engines inline your code?)
When the time comes, or when caller is null (when it is global code), you may still be able to get textual stacktrace (new Error().stack) and current script element (document.currentScript), but their capabilities are pretty limited.
You can get a script element's code - if any - with its textContent or innerHTML property.
Your question sounds like an XY Problem. You want to do something that no modern language is meant to do, but never say for what purpose.
Try to describe your real problem.
Functions have a toString() method. (Yes functions have methods!)
var fn = function() { alert('hello') };
fn.toString() // "function() { alert('hello') };"
So you can alert it:
alert(fn.toString());
You can log it to the js console:
console.log(fn.toString());
Or even write it to the page.
document.getElementById('someID').innerHTML = fn.toString();
However, this won't work for every function in the universe.
[].push.toString()
"function push() { [native code] }"
Some functions are not implemented with javascript, but in the compiled code of the browser or JS engine. For these environment provided functions, you will get this above less helpful output.
If you're not in strict mode you can go up the stack from something which was referenceable (i.e. a named function expression) using (non-standard) .caller
function getFunctionReference(callback) {
var ref = getFunctionReference.caller;
if (callback) callback(ref);
return ref;
}
Now you can do things like
(function () {
getFunctionReference(alert);
}());
// alerts the .toString of the IIFE
This only works for functions, you can't do this on top level code.
The best way to explore your code is actually with the Console, and you can use the debugger; statement or breakpoints to follow exactly what is happening and when.

javascript: call a function in a closure scope

Is there any way I can override a closure so it does part of what the original closure does? I know there's no straightforward way, but is there some hack? I'm willing to be messy...
<html>
<head>
// I DON'T CONTROL THIS CODE!!!
<script>
;(function() {
function _dothing() {
alert("_dothing");
}
function _doit() {
_dothing();
alert("_doit");
}
window.K = { doit : _doit };
})();
</script>
</head>
<body>
// I DO CONTROL THIS CODE
<script>
function mydoit() {
alert("mydoit");
_dothing(); <-- THIS FAILS, IS THERE ANY WAY TO SUCCEED? :(
}
window.K.doit = mydoit;
window.K.doit();
</script>
</body>
</html>
I think you can use jQuery to get the content of the script tag and after that you can use eval see this question.
When you put code inside this:
(function() {
})();
it's called a self invoking function, and creates a scope that you can't access (just like not being able to access a function's scope anywhere else...only inside of it) - it is run as soon as it is declared. The fact that you can call window.K.doit is because the code extends the global window object. Since you have access to window everywhere, it can be called, but only with window.K.doit or K.doit. This is how jQuery plugins are normally defined - they extend the global jQuery object without exposing any of their code directly. Sooooo no, you are not able to access it unless you do something like what the other answerer proposes - but be careful with using eval, as TECHNICALLY, any script could be inserted and you could "assume" it's right/trusted and eval it.
You can try something like this (I know this is very nasty, but, as others pointed out, it seems to be the only way):
function mydoit() {
alert("mydoit");
_dothing();
}
var f = new Function(document.scripts[0].text.replace(/(}\)\(\);\s*)$/, "window._dothing = _dothing;\n$1"));
f();
window.K.doit = mydoit;
window.K.doit();
Tested on Firefox, Chrome and IE8.
Beware: this is creating a hole new context, it's not the same as the already created.
It is calling just a copy of _dothing, not the original.
You have to create a global variable from within the anonymous / self executing function: this tutorial will show you how: http://professionalaspnet.com/archive/2012/07/29/Make-Your-JavaScript-Better-With-Self-Executing-Anonymous-Functions.aspx

Contending with JS "used before defined" and Titanium Developer

I have a lengthy JavaScript file that passes JSLint except for "used before it was defined" errors.
I used normal function declarations, as in...
function whatever() {do something;}
as opposed to...
var whatever = function(){do something;};
and consistent with Steve Harrison's reply to an earlier post...
Assuming you declare all your
functions with the function keyword, I
think it becomes a programming-style
question. Personally, I prefer to
structure my functions in a way that
seems logical and makes the code as
readable as possible. For example,
like you, I'd put an init function at
the top, because it's where everything
starts from.
... I like seeing the functions in an order that makes sense to me.
The script functions perfectly in the several browsers tested (e.g., FireFox, Safari, Mobile Safari, Fennec, IE, Chrome, Midori, etc.).
Here's the problem: I want to use the script inside of an iPhone app being built with Titanium but its compiler stops with "used before defined" errors.
How can I get around this?
This might be a stupid question but also... If functions need to be called in a particular order, how does one resolve the matter of a called function needing to call back to the function that originally called it? For instance...
function buildMenu(){
Display a list of five menu items, each of which calls a function to build the associated screen.
}
function screen1() {
Display the screen associated with menu item #1.
}
If the functions need to be declared in order, function screen1 would need to precede function buildMenu. But what if, under certain conditions, screen1 cannot be built and hence wants to redisplay the menu (i.e., calling a function that is technically not yet declared)?
Oh yeah... one more question: Are there websites or programs that automatically re-sequence the functions rather than requiring the programmer to do it manually?
No, EM's answer is NOT the right solution. Try running this JavaScript:
(function () {
foo(); // right
var foo = function () {
console.log("wrong");
};
foo(); // wrong
function foo() {
console.log("right");
}
foo(); // wrong
}());
This is because the interpreter will first read the function declaration, create the name foo as a function that prints "right", then reads the var statement, and find that there is already a name foo so it will skip creating a new variable with the value undefined, as normally happens. Then it processes the code, line-by-line, which includes an assignment to foo. The function declaration does not get reprocessed. Maybe this will behave differently in Titanium, but try this in Firebug and you'll get what I got.
A better solution is:
var screen1, buildMenu;
screen1 = function () { buildMenu(); };
buildMenu = function () { screen1(); };
This will also pass JSLint, and produce the correct behavior.

Categories

Resources