I tried to write a function on a JS file and another function with the same name in the page.
I expected an error but no error came and I got only the function from the JS file to execute.
How is this possible? Even if I write a function in a separate JS file, everything is rendered in a single html file. Then how come it is possible?
<script type="text/javascript" language="javascript" src="JScript.js"></script>
<script language="javascript">
function Boo() {
alert("Hai new");
}
</script>
<button onclick="Boo();">Click</button>
and in the JS file
function Boo() {
alert("Hai");
}
One aspect that not many people ever think about with JavaScript is
that if you define multiple functions
with the same name then the last one
defined will be the one that actually
runs. JavaScript functions are not
polymorphic the way that functions in
many other languages are in that
JavaScript doesn't care if the actual
arguments defined for the functions
are different as it can't distinguish
between them on that basis. Where in
other languages you might have
myfunc(oneparm) and myfunc(parmone,
parmtwo) as two separate functions
with the one that gets run depending
on the number of parameters passed, in
JavaScript the last one defined will
always be the one run regardless of
the number of parameters.
http://javascript.about.com/library/blpolyfunc.htm
Named functions in javascript are more like variables. If you change the value of a variable, no error occurs, the variable simply has a new value. The same can be said of a function in javascript.
In JS you can redefine functions. A subsequent function with the same name as another function will overwrite it. (Subject to scope)
Because it gets overwritten by the latest one.
JavaScript is highly forgiving in these aspects (like redeclaring a variable or function). The latest one hides or override the previous ones.
In your case, I assume that the js file was loaded after the function Boo inside the html was parsed. Thus when you click on the button, the definition of Boo in js file is the only Boo available.
Case 1: Internal JS has higher priority than External JS, that s why the function written in internal JS override/replaces the other function(with same name) written in external JS file. Example Below:
Internal JS file:
<script type="text/javascript" language="javascript" src="JScript.js"></script>
<script language="javascript">
function Boo()
{
alert("Hai Internal");//this function will simply override the one
//written in external JS file
}
</script>
<button onclick="Boo();">Click</button>
External JS file: JScript.js
function Boo()
{
alert("Hai External");
}
Case 2: If two function with same name exits in the same file,
the one that is declared last(close to the bottom of the file) will override the function above of it. Example below:
<script language="javascript">
function test() {
alert("test 1");
}
function test() { // this will override/replaces the above function
alert("test 2");
}
</script>
Related
I had made flag and made my previous question deleted because of missunderstanding.
I'm working on a classic asp project.
let's say you have so many <script></script> tags in your code.
For instance:
line 10: <script> ..function 1 definition here..</script>
line 200: <script> .. function 2 definition here..</script>
line 5000: <script> ..function 3 definition here..</script>
also at line 6000: I have another tag which is trying to call function1.
is that possible without using *.js file ?
For instance:
line 6000:
<script> function1(); </script>
Those scripts are not defined in <head> tag.
I know its not useful but I need to know is there any way of it or not.
Hope its more clear now!
anything inside the script tags gets run immediately. if you define function a() in your first script element, then it will add a function called a to your global namespace. any javascript you execute later on in other script elements will have access to it.
<script type="text/javascript">
function a() {
alert('hi');
}
</script>
...
<script type="text/javascript">
a();
</script>
Yes, that is possible, assuming function1 is in the global scope (e.g. not in a wrapper function/self-invoking function).
Of course it is possible . You just need to define it in global namespace. Here is the link which should give you an idea and better understanding. It also includes very simple examples.
I have a html code in which i had two javascripts. I want to call the function of 1 javascript into another. Below given is the structure of my javascript.
<html>
<head>
<script>
function a()
{
//function code
this.parent["asd"].b(); //problem in dis line
}
</script>
<body>
<script>
var asd= new Asd();
function b()
{
//function code here
}
</script>
</body>
</html>
It works fine when i use it locally or from a web server. But if i upload this page in my facebook application, the parent class points somewhere else since its inside a iframe. How to resolve it. Is there any other way to call the function.
You can:
=> combine both javascripts which you want to use in one
or
=> include a file first of which function you want to use in another javascript so it will automaticall get the value from that javascript file.
Its doesn't matter that you have written function in same script tag or in another it easily called with function name only like below
<html>
<head>
<script>
function a()
{
//function code
b(); //problem in dis line
}
</script>
<body>
<script>
var asd= new Asd();
function b()
{
//function code here
}
</script>
</body>
</html>
It is always better to combine all your Javascript files into one complete js file. So, you can just merge both your javascript files together. That would also save you from this trouble. You can also see this thread.
Can you try eval("asd").b(); instead of this.parent["asd"].b();
it doenst matter. you can call any function already refered in the HTML as in the same file. because ultimately everything in same page.
Thank u all. i got the solution. i removed the function word from the javascript. now its working fine.
I'm using jQuery Mobile Ajax navigation feature, And I need to change a variable that is defined inside external js file, So I can't put my definition before I load that js file...
So, How to change value of a variable for external javascript file after the js file is defined?
(That external js file includes events)
So this question is not duplicate of that question.
Update
My JS File contains events, something like this: $(document).on('mousemove','#main',function() { /*something*/} );
And I need that variable. Is it possible to pass variable to that?
I have tried simply changing that variable i = 5;, but I'm getting undefined error.
Update 2
The external JS file is something for some pages that are almost same, but a little different, just one or two parameters.
And I simply want to pass the parameters to that JS file. Is it possible? How?
Let's assume http://www.example.com/external.js defines variable foo, which you want to change.
<script src="http://www.example.com/external.js"></script>
<script type="text/javascript">
foo = "my new value";
</script>
This assumes that external.js defined foo in the global scope. If it's defined in an anonymous function or similar, you won't be able to change the value.
Depending on what you're doing, you can just set the variable and it'll work. Example:
// JS file
blah = "Hello";
function doSomething() {
alert(blah);
}
// HTML file
blah = "I'm a fish";
doSomething(); // alerts "I'm a fish";
Alternatively, pass the variable as an argument to relevant functions instead of using global variables.
I am referencing JavaScript as follows on an HTML page:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false®ion=GB"></script>
<script type="text/javascript" src="js/shared.js"></script>
<script type="text/javascript">
$('document').ready(function() {
// In-page code: call some functions in shared.js
});
</script>
The functions defined in shared.js are not wrapped inside $('document').ready. So:
Is it safe to assume that functions defined in shared.js are available to the "in-page code"?
If I pull out the in-page code into a separate file called local.js (keeping it wrapped in $('document').ready), is it still safe to assume that functions defined in shared.js are available?
Finally, is the fact that I'm not wrapping shared.js inside $('document').ready a problem? I'm finding that if I do wrap it, its functions are no longer available to the in-page code.
The reason for question 3 is that I'm hitting this problem: Uncaught TypeError: Property ... is not a function - after page has loaded
and wondering if it is something to do with how I've organised my code.
UPDATE: Thanks for the answers. It's now clear that using $('document').ready in shared.js would remove those functions from global scope. However, I just want to clarify the original question in point 3.
Can I assume that if I do the following:
inside my in-page code, loaded inside $('document').ready, call a function from shared.js
have the function in shared.js refer to jQuery, Google Maps, or elements on my page
there will be no problems?
In other words, is it safe to assume that the page will have loaded by the time the functions inside shared.js are called, even if I'm not wrapping everything in that file inside $('document').ready?
Is it safe to assume that functions defined in shared.js are available to the "in-page code"?
Yes, As long as those functions are injected into global scope
If I pull out the in-page code into a separate file called local.js (keeping it wrapped in $('document').ready), is it still safe to assume that functions defined in shared.js are available?
Yes, As long as local.js is included after shared.js AND shared.js injects functions into global scope.
Finally, is the fact that I'm not wrapping shared.js inside $('document').ready a problem? I'm finding that if I do wrap it, its functions are no longer available to the in-page code.
Wrapping functions in document.ready takes them outside of global scope.
var foo = 4; // global
$(function() {
var bar = 5; // local
});
foo = bar; // error
You need to inject variables in global scope, this is as easy as doing
$(function() {
/* all your code */
window["SomeGlobalVariable"] = someFunctionIWantGlobal;
});
Yes
Yes
Maybe. If you wrap code in a function you will lose global access to functions defined. For the most part that's a good thing - not polluting the global namespace. You can still access these functions in the global namespace if instead of function foo(){} you do window.foo = function(){};.
This is all irrelevant however, because you either need a dom ready listener or you don't - depending on whether or not you're trying to access the dom in that code. If yes, then wrap it, if not, then don't. As mentioned, either way you can close over your code so as not to pollute the global namespace, or pollute it if you so desire.
It is safe to assume (if the definitions are not hidden inside a closure that cannot be accessed).
//shared.js
function DoThis() {}
function DoThat() {}
It will still work, just embed local.js after shared.js
<script type="text/javascript" src="js/shared.js"></script>
<script type="text/javascript" src="js/local.js"></script>
It did not work, because the functions were wrapped in a closure (the one that will be run on domready), so they are only available inside that closure
$(document).ready(function () { //this is a closure!
function DoSg() {}
//DoSg is only available inside the closure
//cannot be accessed from the outside, it's defined inside
});
Also, it is unnecessary to put function definitions into $(document).ready(). The part that matters is when you call these functions, that should be inside .ready() (well, if it involves DOM stuff or anything that should be done after page load).
Your code organisation is fine as presented. Any functions defined in "shared.js" will be available to the rest of your page, including your $('document').ready(function() block.
However, if you place the functions in shared.js within that block, then you limit the code's scope to the $('document').ready(function() (i.e. nothing else in the page can use it) -- so that's not the way to go if you want to make stuff in "shared.js" available to other parts of your code / application.
Finally, is the fact that I'm not
wrapping shared.js inside
$('document').ready a problem? I'm
finding that if I do wrap it, its
functions are no longer available to
the in-page code.
If you wrap your function inside document.ready those function are not available in the global scope, as function have local scope (I.E inside the function where they are contained)
I have two external JavaScript lib files I have to load on same JSP page. They both have a function called "autoSave()", both without parameters. I cannot modify their signature as they are not my script files.
How can I call a function in script A or script B explicitly? How is the precedence decided?
The function defined by the second script will overwrite the function defined by the first one.
You can save a copy of the function from script A before including script B.
For example:
<script type="text/javascript" src="Script A"></script>
<script type="text/javascript">
var autoSave_A = autoSave;
</script>
<script type="text/javascript" src="Script B"></script>
<script type="text/javascript">
var autoSave_B = autoSave;
</script>
Note, by the way, that if script A calls autoSave by name, the script will call the wrong autoSave and (probably) stop working.
You could solve that by swapping in the autoSave functions before calling functions from either script using wrapper methods.
Well, IMO your libraries should be namespaced, so you could easily call lib1.autoSave() or lib2.autoSave(arg).
The goal is to use as few global variables as possible.
Give a look to the following articles:
Namespacing your JavaScript
JavaScript Namespacing
A second function declaration for the same function name overwrites an earlier one, so it will depend on the order your scripts are included.