开发者

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

开发者 https://www.devze.com 2022-12-10 02:03 出处:网络
I have a variable named age and a function named AGE.Ignore the problem I am having with JScript beign case insensitive at the moment, i.e. age(dob) and AGE(dob) both work...

I have a variable named age and a function named AGE. Ignore the problem I am having with JScript beign case insensitive at the moment, i.e. age(dob) and AGE(dob) both work...

Why does JScript try to开发者_开发百科 use the age variable as a function? My best guess would be that jScript is treating the function declaration as both declaration and expression...

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


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

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


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


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

That should explain why you can't do this. On the line with the error, it's not clear what you're assigning to foo: it could be age, the numeric variable with a value of 32. But it could also be age, the function variable.

Put another way, this is perfectly legal:

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

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

and so is this:

function print42() {
    return 42;
}

print42 = function() {
    return 32;
}

print42(); //legal - returns 32

If you're worried about avoided conflicts, you could try putting your functions inside an object instead:

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

}

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

Note the '$' in the names. There's nothing special there. '$' is perfectly fine for use as part of an identifier name, and you want to make sure your name is unique. However, thanks to jQuery and the like the $ "secret" is starting to get out, and so you want to also add a little something extra to keep things unique.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消