Why is there a conflict between variables and functions with the same name in JScript?

I have a variable named age and a function named AGE. Ignore the problem I am running into with JScript inconspicuous case for now, i.e. age (dob) and AGE (dob) work ...

Why is JScript trying to use the age variable as a function? My best guess would be that jScript treats the function declaration as an expression and an expression ...

function AGE (birthDate) { 
     return cmd.Age (birthDate); 
};


var age = 32;
var foo = age; // Error on AGE function

I am using ScriptControlClass in a C # application and using JScript as a simple embedded language to provide some simple expression of complexity of complexity for my user base ...

+2


source to share


3 answers


This is the standard JavaScript syntax described in the summary on this JavaScript tips page . You should take a look at the JavaScript link; many recommend JavaScript: Good parts written by the original JavaScript author, but you should do your research before buying the book.



+1


source


Make sure you don't give a function and variable with the same name. If you have a my_cat variable and a my_cat function, JavaScript will forget what the function is supposed to do or what value you stored in the my_cat variable. Because of this strange behavior, and because function names are case sensitive, it makes sense to have a different naming convention for functions than for variable naming.



+2


source


In JScript / javascript, functions are first class objects. Thus, functions are also variables that you can pass, reuse, replace, etc.

This should explain why you cannot do this. On the line with the error, it is not clear what you are assigning to foo: it could be age, a numeric variable with a value of 32. But it could also be age, a functional variable.

In other words, it's perfectly legal:

function age(birthDate) { 
   return cmd.Age(birthDate); 
};

var d = new Date();
var foo = age;
foo(d);

      

etc:

function print42() {
    return 42;
}

print42 = function() {
    return 32;
}

print42(); //legal - returns 32

      

If you are worried about avoidable conflicts, you can try putting your functions inside an object:

var $$MyProjectName = function()  { 
    var MyFunctionName = function() {
        // do something
    }

}

// later
var $$MyProjectInstance = new $$MyProjectName();
$$MyProjectInstance.MyFunctionName();

      

Notice the "$" in the names. There is nothing special there. "$" is great to use as part of an identifier name, and you want to make sure your name is unique. However thanks to jQuery etc. The "secret" is starting to come out and so you want to add a little more to keep things unique.

+2


source







All Articles