Javascript object name usage issue.. i think
So i'm setting up an object with private and public methods. Basically using the following format:
var Utility = function() {
var prive1, priv2, priv3;
function privateMethod1() { //do something }
return {
publicFunc1: function() { //do something different }
publicFunc2: function() { //do something else }
}
}
But i'm worried about some of the situations i'm coming across where publicFunc2 nee开发者_开发问答ds to call publicFunc1. For Example the way I would do this atm is:
publicFunc2: function() { Utility.publicFunc1(); //then do something else }
is this OK? It runs, but it seems weird and VS2010 doesn't give me . I believe that if someone was to change the line var Utility = function() { --> to --> var Utility2 = function() {} then essentially everything would be broken from within the object and that seems wrong... but i'm at a loss on what i should actually be changing. Should i be making all methods basically private and then mapping to a public function? EX:
{
function privateFunc1() {}
return {
publicFunc1 : privatefunc1
}
}
or should i have a completely different approach to accomplish the idea of private and public methods and variables?
return {
publicFunc1: function() { },
publicFunc2: function() { this.publicFunc1() }
}
If you want to call some function - give it a name and call it by that name:
var Utility = function() {
var prive1, priv2, priv3;
function privateMethod1() { //do something }
function Func1() { //do something different }
function Func2() { Func1(); //do something else }
return {
publicFunc1: Func1,
publicFunc2: Func2
};
}
Call of local function by name is always faster than any other method of call in JS.
In cases like this remember the YAGNI (You ain't going to need it) concept. Sure, think about the best way to organise things but code for now intially and then refactor it later if needed.
Do the functions need to public or are you second guessing the functionality that may be needed later? Make them private, have a single public method for now. Refactor later if needed. Keep it simple.
精彩评论