By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,605 Members | 2,153 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,605 IT Pros & Developers. It's quick & easy.

Duplicate Definition in JavaScript.

dmjpro
100+
P: 2,476
Today i encountered a typical thing. So far what i knew that JavaScript had a scope inside a function but it was not there. I think in newer version of JavaScript it is introduced, in older version there may be. Anyway .....
Have a look at my code snippet ....

Expand|Select|Wrap|Line Numbers
  1. function test(){
  2. var s = "Hello!";
  3. var s = "Hi!";
  4. alert(s); //it alerts the latest value of s, and here is no duplicate definition of s
  5. }
  6.  
Expand|Select|Wrap|Line Numbers
  1. function test(){
  2. //some code
  3. }
  4.  
  5. function test(){
  6. //some latest code
  7. }
  8.  
Whenever i call test it executes the latest code, here is also not duplicate definition. How JavaScript handles it?
Please explain.
Aug 7 '08 #1
Share this Question
Share on Google+
3 Replies


gits
Expert Mod 5K+
P: 5,343
with you first example you REdeclare var s within the function ... when you set the javascript-engine to handle the interpretation of the code in strict-mode in firefox/mozilla then the error console will show you that as a warning.

the second is OVERwriting ... basically functions are declared in the window-scope and there you overwrite the first with the second ... basically what you do is:

Expand|Select|Wrap|Line Numbers
  1. this.test = function() {
  2.     // some code 
  3. }
  4.  
where this is the window-object's scope ...

kind regards
Aug 7 '08 #2

rnd me
Expert 100+
P: 427
scope is only preserved and layered in functions:
Expand|Select|Wrap|Line Numbers
  1. function test(){
  2.   function test(){
  3.     return test;
  4.   }
  5.  return test;
  6. }

tests:

test().toString() // =
Expand|Select|Wrap|Line Numbers
  1. function test() {
  2.     return test;
  3. }
  4.  
test.toString() // =
Expand|Select|Wrap|Line Numbers
  1. function test() {
  2.  
  3.     function test() {
  4.         return test;
  5.     }
  6.  
  7.     return test;
  8. }
  9.  
  10.  
Aug 7 '08 #3

gits
Expert Mod 5K+
P: 5,343
ahh ... and to put FF into strict-mode ... type in the address-bar: about:config there a filter appears and you type in the filter: javascript.options.strict ... set its value to true -> see what a bunch of errors and information you now get in the console additionally :)

kind regards
Aug 7 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.