0

While I browse for some JS Code, I found the code.

Sample code:

arg = "TEST ALERT MESSAGE";
MyFunction(arg);

function MyFunction()
{
alert(arg)
}

Above MyFunction() is given the alert message, but there is no parameter to receive the incoming arugment.

But when I change the 'arg' variable(in the function and out side the function 'arg'), it is not working.

How it is possible?

Thanks in advance

2
  • If MyFunction does not have a local version of arg, it will try refer to a property named arg in the outer scope. Failing that you will get undefined. Commented Jun 13, 2013 at 6:06
  • A function without any pre-defined arguments can still take arguments, they are dynamic and can be accessed through the arguments pseudo array. Commented Jun 13, 2013 at 6:09

1 Answer 1

1

Variable scope in javascript doesn't work the way you think. in order to make that variable 'private' try:

var arg = "not private";
function privateMSG(){
var arg = "private";
  function alerter(){
  alert(arg);
 }
  alerter();
}

MDN has a much better explanation in the Nested functions and closures section

Sign up to request clarification or add additional context in comments.

4 Comments

Actually they do. But their scope is chained with the one they are defined in. Variable lookups will start in the function's scope and if they cannot be resolved there, the lookup will proceed along the chain, finally ending up with undefined if found nowhere.
is this power of javascript or any like bug?. I thought there is no security
It's by design. You use closures to make stuff private.
Now I can understand. Thanks Friends

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.