Friday, June 17, 2011

How to solve the problem of having the same name in JavaScript variables and functions?

JavaScript is a scripting language, which is widely used in Web Applications. However, in practice, many people only treat JavaScript code as a collection of variables and functions. Because of many such usages, it brings a very common trouble problem - how to solve the problem of variables and functions have the same names. Java introduces package mechanism to solve this problem. So can we also introduce this mechanism to solve it? The answer is yes. The solution is as follow.
Original Code:
var v1 = "v1";
function f1() {
 return v1 + v2;
}
New Code:
function Common() {}

Common.v1 = "v1";

Common.f1 = function(v2) {
 return v1 + v2;
}
Using new code, we can use Common.v1, Common.f1. "Common" is treated as package of this code. This usage is also called JavaScript static object.

No comments:

Post a Comment