JS how to avoid using "this" [duplicate] - javascript

This question already has answers here:
Difference between this and self in JavaScript
(5 answers)
Closed 4 years ago.
I recently watched a youtube tutorial, and the guy did something interesting in the series (it's node.js game tutorials by Raining Chain). His constructor looks like this:
const MakeStuff = function(param1, param2) {
const self = {};
self._param1 = param1;
self._param2 = param2;
// and so on...
return self;
}
const someStuff = MakeStuff(param1, param2);
I then checked google for what "self" meant and it found out it's something similar to "this"... It's really confusing me now. At first I thought he's just naming it "self" to mimic "this", but avoid using it.
Also, JSLint really hates "this", and I hate to dumb down JSLint and disable or edit options (ocd), so I'm trying to figure out how am I gonna use classes, and avoid using "this" inside classes constructor.
I figured I'd copy/paste my class function in babeljs and see what the class syntax actually does under the hood, but I got even more confused.
I have around 2k lines of code in my game, and 1.5k are just classes with getters, setters and static methods.
What does the code above actually do? What does self mean? Can I use JS classes and avoid using "this" in constructors? Why does JSLint even hate "this"? Should I rework my code using the example above and bind getters, setters and static methods using prototype?
Thanks!

What does the code above actually do?
const MakeStuff = function(param1, param2) {
const self = {};
console.log(self);
self._param1 = param1;
self._param2 = param2;
// and so on...
return self;
}
const someStuff = MakeStuff(1, 2);
console.log(someStuff)
This above code simply calls a function which accepts two parameter and return an object.self inside this function is merely a variable
What does self mean?
Unless specifically set self refers to the window object.But in the above function const self is not window.self
console.log(self)

As of now, self is used by other languages in place of js' this; it is a reference to the instance's context. In this use case, he's not writing a constructor, but a factory. self is little more than a naming convention here. It would make no difference if he wrote:
const MakeStuff = function(param1, param2) {
const obj = {};
obj._param1 = param1;
obj._param2 = param2;
// and so on...
return obj;
}
const someStuff = MakeStuff(param1, param2);
Also, +1 to brk for mentioning that self, unless re-set, references window.

this is one of the important aspects of JavaScript but one of the most poorly understood. It is absolutely essential to understand to do any Object Oriented Programming within JS which is essential to game design.
I would recommend learning about scope and how this applies to different things in different scopes.
http://web.archive.org/web/20110725013125/http://www.digital-web.com/articles/scope_in_javascript/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://javascriptplayground.com/javascript-variable-scope-this/
http://ryanmorr.com/understanding-scope-and-context-in-javascript/
Essentially when you run a function such as
function window_scope() {
this.foobar;
}
this is the window in browsers or whatever variable is defined as the global scope. Meaning this.foobar is equal to window.foobar
When you do new while calling a function such as var newfoo = new foo()
function foo() {
this.foobar;
}
this has suddenly become a reference to newfoo. Meaning this.foobar is equal to newfoo.foobar This allows you to make objects that don't need a reference to the actual local variable newfoo

in your case self is just the name of an constant.

To me MakeStuff is just a function, not a constructor. And self doesn't have anything to do with this in the code you provided. Here it's just a variable inside the function that gets assigned some keys and elements param1 and param2.
const MakeStuff = function(param1, param2) {
const returnedElement = {};
returnedElement ._param1 = param1;
returnedElement ._param2 = param2;
// and so on...
return returnedElement ;
}
const someStuff = MakeStuff(param1, param2);
Sometimes you will need to use self (some use that) to access this but within another scope.
A great explanation you can find on another SO thread is:
var self = this;
[This is] keeping a reference to the current object, so later when you call [self] you're calling that method on that object, not any other.

Related

Passing a window object into Javascript namespace

I'm trying to better understand namespacing in javascript and found an example of a javascript Immediately-invoked Function Expression that is taking the window object as a parameter. Here is the code from it:
var CG = CG || {};
CG.main = (function(window) {
var FOCAL_LENGTH = 8.0;
var context, width, height, startTime;
var init = function() {
var element = document.getElementById("canvas1");
context = element.getContext("2d");
width = element.width;
height = element.height;
startTime = (new Date()).getTime() / 1000.0;
tick();
}
var original_onload = window.onload || function() {};
window.onload = function() {
original_onload();
CG.main.init();
}
return {
init: init,
draw: draw_shape,
clear: clear_canvas
};
}(window));
At the end of the namespace definition, there is a line with window in parenthesis which I am confused as to the functionality of. I think that the purpose of adding the parameter of window to the end of the definition is to bind the global window variable to the namespace which will then add different properties to the window, but I can't really be sure.
In another example there is a random variable name passed into the definition of a namespace, and at the end of the namespace definition, the actual name of the namespace is passed as a parameter:
var namespace = namespace || {};
// here a namespace object is passed as a function
// parameter, where we assign public methods and
// properties to it
(function( o ){
o.foo = "foo";
o.bar = function(){
return "bar";
};
})(namespace);
console.log(namespace);
So there are really a couple of questions here:
What is the functionality of passing a parameter at the end of the namespace definition?
If my intuition for how this all works is incorrect, what is the general structure for this kind of namespace creation javascript?
Clearly I'm very new to this so any help would be appreciated, thanks.
I will try to explain this as well as I can but my understanding of it comes from Kyle Simpson. He's awesome, you should look him up. :-D
You are asking a question about immediately invoked function expressions (IIFE), passing arguments to them, and why someone would do that.
First, the reason IIFEs are being used in this context is to restrict the scope of variables.
This is important because as programs become larger and many pieces are added on you can easily have conflicts from one variable to another.
app.js could have
variable = "thing";
and shortly after somethingelse.js could have
variable = "not thing";
That is a huge problem. It is avoided in javascript by creating "modules" or functions that immediately run and run once.
That way, the variables and methods you create in your function don't "pollute the global scope/namespace."
BUT, what if you NEEDED or WANTED something to be available on the global window object?
Well, you could do that by adding it to the "window" which is the global scope in javascript.
(function Module(window){
var _thing = "private thing that only exists in this function";
window.thing = _thing;
//IS NOW AVAILABLE GLOBALLY AND EXPLICITLY ON WINDOW OBJECT
//window.onload you can wait for DOM/page before running the rest
})(window);
You also could have named it anything you wanted inside your function:
(function niftyModule(global){
global.variable = "nifty text!";
})(window)
This becomes especially important when you are using multiple libraries.
For some reason, everyone likes to use "$" as the representation of their library so you can access their private methods (which are really just functions inside an IIFE too! (its a really popular way to build good stuff).
So, what if you are using jQuery and 2 other libraries that also use $ to access their public methods/api??
Easy, you can assign which one you want to assign what variable inside your function/module scope by passing it in as an argument!
(function NiftyModule(window, $){
//Now, every time you use $ in here it means jQuery and not something else!
})(window, jQuery);
It is important to play around with functions and scope. Build some variables in different ways.
For example, is....
var text = "nifty text";
the same as
text = "nifty text";
How about if you do the same thing inside functions? How do those two versions differ?
Also, get used to building your own programs in IIFEs and properly restricting the scope of the code you are writing.
You can also return objects from functions which have the methods and variables you want to access globally on them without adding them to the window object.
It is complicated at first but in the future it saves you a lot of trouble and bugs!
Finally, In your example of:
//initialize a global variable called namespace. If this already
//existed then assign it the previous values. If not, make it an empty
//object.
var namespace = namespace || {};
//pass namespace into an IIFE. Within the IIFE refer to namespace as "o"
(function( o ){
//assign a variable to namespace
o.foo = "foo";
//assign a method to namespace
o.bar = function(){
return "bar";
};
})(namespace);
//now when you log namespace it will have those properties.
console.log(namespace);

Variable privacy in Javascript's behaviour delegation pattern

Since my last question, I've been studying Javascript's prototype model and trying to get rid of the OOP vision I inherited from other languages (pun slightly intended).
I went back to basics and read Crookford's Javascript: The Good Parts, along with You Don't Know JS material and decided to stick with the so called behaviour delegation.
Restructuring my previous example implementing behaviour delegation and namespacing, I wrote:
var GAME = {};
(function(namespace) {
var Warrior = {};
Warrior.init = function(weapon) {
this.setWeapon(weapon);
};
Warrior.getWeapon = function() {
return this.weapon;
};
Warrior.setWeapon = function(value) {
this.weapon = value || "Bare hands";
};
namespace.Warrior = namespace.Warrior || Warrior;
})(GAME);
(function(namespace) {
var Archer = Object.create(namespace.Warrior);
Archer.init = function(accuracy) {
this.setWeapon("Bow");
this.setAccuracy(accuracy);
};
Archer.getAccuracy = function() {
return this.accuracy;
};
Archer.setAccuracy = function(value) {
this.accuracy = value;
};
namespace.Archer = namespace.Archer || Archer;
})(GAME);
So, everytime I copy a new Archer object:
var archer1 = Object.create(GAME.Archer);
only this object will be created, conserving memory.
But what if I don't want to expose "accuracy" attribute? The attribute would only increase by calling a "training()" method or something similar. I tried to use var accuracy inside the anonymous function, but it turns into kind of static variable, all instances of Archer would share the same value.
The question: Is there any way to set a variable as private while still keeping behaviour-delegation/prototypal pattern?
I do know of functional pattern as well, Here I succesfully achieved variable privacy, at the cost of memory. By going functional, every new "archer" instance generates a new "Warrior" and then a new "Archer". Even considering that Chrome and Firefox have different optmizations, testings on both report that the Delegation/Prototypal pattern is more efficient:
http://jsperf.com/delegation-vs-functional-pattern
If I go with the pure-object delegation pattern, should I just forget the classic encapsulation concept and accept the free changing nature of properties?
I would try to answer your question with something that is slightly different then this one that tells you how to use a library.
Different in that it will(hopefully) give you some ideas of how can we tackle the problem of private vars in OLOO ourselves. At least to some extent, with our own code, no external lib needed, which could be useful in certain scenarios.
In order for code to be cleaner I've striped your anonymous wrapper functions, since they are not related to problem in any way.
var Warrior = {};
Warrior.warInit = function (weapon){
this.setWeapon(weapon);
}
Warrior.getWeapon = function(){
return this.weapon;
}
Warrior.setWeapon = function (value){
this.weapon = value || "Bare hands";
}
var Archer = Object.create(Warrior);
Archer.archInit = function (accuracy){
this.setWeapon("Bow");
this.setAccuracy(accuracy);
}
Archer.getAccuracy = function (pocket) {
return pocket.accuracy;
}
Archer.setAccuracy = function (value, pocket){
pocket.accuracy = value;
}
function attachPocket(){
var pocket = {};
var archer = Object.create(Archer);
archer.getAccuracy = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]);
return Archer.getAccuracy.apply(this, args)
};
archer.setAccuracy = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]);
return Archer.setAccuracy.apply(this, args);
};
return archer;
}
var archer1 = attachPocket();
archer1.archInit("accuracy high");
console.log(archer1.getAccuracy()); // accuracy high
archer1.setAccuracy("accuracy medium");
console.log(archer1.getAccuracy()); // accuracy medium
Test code above here. (and open your browser console)
Usage
1 ) General practice in OLOO about naming functions on different levels of prototype chain is apposite from OOP. We want different names that are more descriptive and self documenting, which brigs code that is cleaner and more readable. More importantly, by giving different names we avoid recursion loop:
Archer.init = function(accuracy, pocket){
this.init() // here we reference Archer.init() again, indefinite recurson. Not what we want
...
}
Archer.archInit = fucntion (accuracy, pocket){ // better,
this.warInit() // no name "collisions" .
}
2 ) We've created an attachPocket() function that creates internal variable pocket. Creates new object with Object.create() and sets it's prototype to point to Archer. Pause. If you notice, functions that required a private var we have defined so that each of them take one more parameter(pocket), some use just pocket. Here is the trick.
By making wrapper functions like archer.setAccuracy(), archer.getAccuracy()
... we can create closures and call directly functions that need
private var (here pocket) and pass it to them as an argument.
Like so:
function AtachPocket(){
...
var pocket = {};
archer.setAccuracy = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]); // appending pocket to args
return Archer.setAccuracy(this, args);
};
...
}
Essencially by doing this we are bypassing what would have been a normal search for functions in prototype chain, just for functions that have need for a private var. This is what "call directly" refers to.
By setting the same name for a function in archer("instance") like it is in prototype chain (Archer) we are shadowing that function at the instance level. No danger of having indefinite loops, since we are "calling directly" like stated above. Also by having the same function name we preserve the normal, expected behaviour of having access to same function in an "instance" like it is in a prototype chain. Meaning that afther var archer = Object.create(Archer) we have access to function setAccuracy like we would if it had been normal search for function in prototype chain.
3 ) Every time attachPocket() is invoked it creates a new "instance" that has those wrapper functions that pass a pocket argument (all as an internal detail of implementation). And therefore every instance has own, unique, private variable.
You would use functions in an "instance" normally:
archer1.archInit("accuracy high"); // Passing needed arguments.
// Placed into pocked internally.
archer1.getAccuracy(); // Getting accuracy from pocket.
Scalability
Up to now all we have is function that "attaches a pocket" with hardcoded values like Archer.setAccuracy, Archer.getAccuracy. What if we would like to expand prototype chain by introducing a new object type like this var AdvancedArcher = Object.create(Archer), how the attachPocket is going to behave if we pass to it AdvancedArcher object that might not even have setAccuracy() function? Are we going to change attachPocket() each time we introduce some change in prototype chain ?
Let's try to answer those questions, by making attachPocket() more general.
First, expand prototype chain.
var AdvancedArcher = Object.create(Archer);
AdvancedArcher.advInit = function(range, accuracy){
this.archInit(accuracy);
this.setShotRange(range);
}
AdvancedArcher.setShotRange = function(val){
this.shotRange = val;
}
More generic attachPocket.
function attachPocketGen(warriorType){
var funcsForPocket = Array.prototype.slice.call(arguments,1); // Take functions that need pocket
var len = funcsForPocket.length;
var pocket = {};
var archer = Object.create(warriorType); // Linking prototype chain
for (var i = 0; i < len; i++){ // You could use ES6 "let" here instead of IIFE below, for same effect
(function(){
var func = funcsForPocket[i];
archer[func] = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]); // appending pocket to args
return warriorType[func].apply(this, args);
}
})()
}
return archer;
}
var archer1 = attachPocketGen(Archer,"getAccuracy","setAccuracy");
archer1.advInit("11","accuracy high");
console.log(archer1.getAccuracy()); // "accuracy high";
archer1.setAccuracy("accuracy medium");
console.log(archer1.getAccuracy());
Test the code here.
In this more generic attachPocketGen as first argument we have a warriorType variable that represents any object in our prototype chain. Arguments that may fallow are ones that represent names of functions that need a private var.
attachPocketGen takes those function names and makes wrapper functions with same names in archer "instance". Shadowing, just like before.
Another thing to recognise is that this model of making wrapper functions and using apply() function to pass variables from closures is going to work for functions that use just pocket, functions that use pocket and other variables, and when ,of course, those variables use the relative this reference in front of them.
So we have achieved somewhat more usable attachPocket, but that are still things that should be noticed.
1) By having to pass names of functions that need private var, that usage implies that we(attachPocketGen users) need to know whole prototype chain (so we could see what functions need private var). Therefore if you are to make a prototype chain like the one here and just pass the attachPocketGen as an API to the programmer that wants to use your behaviour-delegation-with-private-variables, he/she would had to analyse objects in prototype chain. Sometimes that is not what wee want.
1a) But we could instead, when defining our functions in prototype chain (like Archer.getAccuracy) to add one property to them like a flag that can tell if that function have need for a private var:
Archer.getAccuracy.flg = true;
And then we could add additional logic that checks all functions in prototype chain that have this flg and fills the funcsForPocket.
Result would be to have just this call:
var archer1 = attachPocketGen(AdvancedArcher)
No other arguments except warriorType. No need for user of this function to have to know how prototype chain looks like, that is what functions have need for a private var.
Improved style
If we are to look at this code:
Archer.archInit = function (accuracy){
this.setWeapon("Bow");
this.setAccuracy(accuracy);
}
We see that it uses "pocket" function setAccuracy. But we are not adding pocket here as last argument to it because setAccuracy that gets called is shadowed version, the one from instance. Becouse it will be called only from an instance like so archer1.archInit(...) That one is already adding a pocket as last argument so there is on need to. That's kinda nice, but the definition of it is:
Archer.setAccuracy = function (value, pocket){ ...
and that can be confusing when making objects in prototype chain like Archer.archInit above. If we look the definition of setAccuracy it looks like we should it. So in order not have to remember that we don't have to add pocket as last arg in functions (like archInit) that use other pocket functions, maybe we should to something like this:
Archer.setAccuracy = function (value){
var pocket = arguments[arguments.length -1];
pocket.accuracy = value;
}
Test the code here.
No pocket as last argument in function definition. Now it's clear that function doesn't have to be called with pocket as an argument wherever in code.
1 ) There are other arguably minor stuff to refer to when we think about more general prototype chain and attachPocketGen.Like making functions that use pocket callable when we dont wan't to pass them a pocket, that is to toggle pocket usage to a function, but in order not to make this post too long, let's pause it.
Hope this can give you view ideas for solution to your question.

Hardcore javascript module scope

The problem : I want to iterate over my list of functions, and modify them in place, using code like:
for(var funcProperty in scope) {
scope['_'+funcProperty] = scope[funcProperty];
scope[funcProperty] = wrapFunctionInTryCatchBlock(scope['_'+funcProperty]);
}
I want to do this without explicitly having to go through all my functions, and add them to some object, thereby creating the required scope. I don't want to do that because then all the functions, which call each other, will have to have their names modified and lengthened to become:
funcName becomes scopeObject.funcName : annoying.
I could do this quite easily if my functions were in the global object, i.e, Window, however I don't want to pollute the global namespace, so I have put them in a module, like so:
var MyModule = (function() {
function privateFunc1(...) {...}
function privateFunc2(...) {...}
var public_api = {
coolName : privateFunc1
};
return public_api;
}());
However, I can see and find no way to access the scope object that exists in the immediately executed function call the return value of which is assigned to MyModule.
I tried doing this, from within MyModule:
console.log(this)
To see if we did have access to the scope, somehow, yet, of course, it turned out that this referred to Window.
My question is really: What is the scope object that the methods in MyModule private scope are assigned to, since it is not the global object, and it does exist, since all the functions have implicit access to it. Is there any way I as a JavaScript programmer can explicitly access the scope object and enumerate its properties or is that FORBIDDEN?
I'm not going to rush to accept this as the answer, but I have found one possible solution that I am happy with.
Definition of "happy with" in this case is : minimal extra work, almost no changes to existing code.
The solution
We modify the module code like so:
// $ = wrapFunctionInTryCatchBlock
function $(fun) {
return function() {
try {
return fun.apply(this,arguments);
} catch(err) {
console.log("Error",err,err.stack);
}
};
}
var MyModule = (function() {
var privateFun1 = $(privateFun1(...){...});
var privateFun2 = $(privateFun2(...){...});
var public_api = {
coolName : privateFun1
};
return public_api;
}());
Why this works
We get the desired code modification (function wrapping), essentially in place since the variables assigned to function expressions have exactly the same scope as the original named functions themselves.
A VIM regex to help
I also created a VIM regex to help with this, at least the assignment line anyway:
s/function \(\w\+\)\(.\+\)$/var \1 = $(function \1\2/g

What's the best way to create a JavaScript namespace? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have not yet found a common way on the Internet for creating a namespace in JavaScript.
What's the best way to create a namespace (and please list any downfalls that particular approach might have).
(function() {
var usefulVariable;
var foo = {
bar:function(){ alert('hi') }
};
// leak into global namespace
window.foo = foo;
})();
Only foo is exposed to the global namespace, and it "lives" within your private self executing anon function namespace.
In JavaScript, namespaces can only be achieved through object literals, which can be as simple as this:
var MyNS = {
f1: function() {...},
f2: function() {...}
};
As others have attempted to show, if you want to provide a private scope within your namespace (which is suggested), the following method is the most appropriate:
var MyNS = (function() {
var private1 = "...",
private2 = "...";
return {
f1: function() {...},
f2: function() {...}
}
})();
The book Pro JavaScript Design Patterns (Harmes & Diaz, 2008) provides examples of namespace creation using simple object literals or self-executing anonymous functions, both of which are illustrated in Justin Johnson's excellent answer, and these approaches work well.
Depending on the situation, it might be possible that the namespace already exists and contains members. In such a case, these approaches would destroy any members in the namespace. If this is a concern, one can use an approach similar to this to preserve any existing members, while adding new ones:
var myNamespace = (function(ns) {
ns.f1 = function() { ... };
ns.f2 = function() { ... };
return ns;
})(window.myNamespace || {});
Here, myNamespace is assigned the value returned by the anonymous, self-executing function that receives the parameter ns. As one can see, the value of this parameter is either window.myNamespace or an empty object, depending on whether or not myNamespace has been previously declared.
Here's my favorite way. It's a little unorthodox but it works well.
var MyNamespace = new function(){
this.MY_CONST_ONE = 1;
this.MY_CONST_TWO = 2;
this.MyClass = function (x) {
this.x = x;
}
this.MyOtherClass = function (y) {
this.y = y;
}
} // end of namespace
// ...
var oc = new MyNamespace.MyOtherClass(123);
The interesting thing about it is the closure function is called with new instead of the normal parenthesis, so directly inside of it this refers to the object returned by the function, in other words, the 'namespace' itself.
I generally try to keep it simple and create a global object representing the namespace. If you are using multiple scripts, each declaring the namespace because they might each be used in different applications, then you would probably want to check if the object already exists.
//create the namespace - this will actually obliterate any pre-existing
//object with the same name in the global namespace
//(and this does happen).
//NB ommiting the var keyword automatically chucks the object
//variable into the global namespace - which ordinarily you
//don't want to do
MyNameSpace = {};
//and then create a class/object in the namespace
MyNameSpace.MyClass = {
someProperty: function(){
//do something
},
anotherProperty: function(){
//doing something else
}
};
This is pretty much what everyone else is saying. I'm just giving the really simplistic approach. Main drawback I see is that theoretically the "MyNameSpace" object could already exist - so might want to check that before you create it. Generally, if I'm going to be doing anything more complicated than that I would start thinking of a framework like JQuery or ExtJS which take a lot of pain out of these sort of things.
One more note. Part of the reason why you can't find a common way to do many things in Javascript, like creating namespaces, is that there is always more than one way to skin a cat in Javascript. Most languages are quite proscriptive on how you do things - create classes, are functional or object oriented or procedural. Javascript, on the other hand, is short of keywords and highly flexible. This maybe a good thing or a bad thing - depending on your point of view. But I quite like it.
To share code between scripts, you have to have at least one global variable (unless of course if you would want to do something as silly as appending your variables to an already existing object such as window.Object.
Even if you use the module pattern, you need to have a common place to share code, so, say e.g. you have three scripts:
core.js
utils.js
Then we can in the core.js script file have a module:
(function(global) {
var coreModule = {};
var MY_CONSTANT = 42
var meaningOfLife = function() {
return MY_CONSTANT;
};
coreModule.meaningOfLife = meaningOfLife;
global.myRootNamespace = coreModule;
}(this));
in the utils.js:
(function(root) {
var utilsModule = root.utils = {};
utilsModule.bark = function() {
console.log("WOOF!");
};
}(myRootNamespace));
Here, we see the use of the augmentation module pattern, and namespacing the functionality depending on the nature of the functionality. This specific implementation overwrites the value of the utils property on the myRootNamespace object. However, we can write it so that it does not:
(function(root) {
var utilsModule = root.utils = root.utils || {};
utilsModule.bark = function() {
console.log("WOOF!");
};
}(myRootNamespace));
If one doesn't want to use the module pattern, we can use a simple function to define namespaces for us in a non destructive manner:
var ensureNamespace = function recur(ns, root) {
var parts = typeof ns === 'string' ? ns.split('.') : ns;
var r = root || this;
if (parts[0]) {
var next = parts.shift()
r[next] = r[next] || {};
return recur(parts, r[next]);
}
return r;
};
// maybe another file:
(function(){
var baz = ensureNamespace("foo.bar.baz");
// baz === window.foo.bar.baz;
baz.qux = "Yep...";
}());
see this excellent article for more insight.
You can combine the answers you have received so far and accomplish much;
var Foo; // declare in window scope.
(function(){
var privateVar = "BAR!";
// define in scope of closure where you can make a mess that
// doesn't leak into the window scope.
Foo = {
staticFunc: function(){ return privateVar; }
};
})();
I generally avoid window.xxxx = yyyy; as it does not always play nicely with visual studio intellesense. There may be other issues but none that I know of.
I believe the module pattern has shown that it is the way to go. Object Literal Name-spacing exposes everything to the caller code outside the namespace which is essentially not a very good idea.
If you insist on creating Object Literal Namespaces, read this tutorial. I find it easy and short and I believe is very through:Object Literal Namespace (OLN) in Javascript

Is my javascript coding style following best-practice?

What is the 'best practise' with regard to coding style.
Should I use _ for private members?
Should I use this._privateMember?
Please re-write my code in proper style if its wrong:
(function()){
var _blah = 1;
someFunction = function() {
alert(_blah);
};
someOtherFunction = function {
someFunction();
}
}();
I would read this and incorporate any part you agree with:
http://javascript.crockford.com/code.html
You do not have to agree with all of it
I don't think there is one. Use a prefix if you think it helps.
I use _ for private members because it distinguishes them which can be quite helpful in Javascript when you have variables coming from all over the place. But they do clutter the code a bit.
I don't use _ for variables that are declared using var. I do however, use _ to denote object members that shouldn't be access directly.
Some people (who are strange in my opinion :P), also prefix variables with a $ if it contains a jQuery object.
As long as you are consistent with what you do, there are no problems.
Aside from just the code you're showing now, you should use Capital Letters to distinguish constructor functions, and camelCase to name instances of objects.
function Foo (val) {
this.set(val);
};
Foo.prototype.get = function () {
return this._dontTouchMePlease;
};
Foo.prototype.set = function(val) {
this._dontTouchMePlease = parseInt(val, 10);
};
var aFoo = new Foo(6);
I think that its generally accepted that if a variable name starts with a _, you probably shouldn't touch it (accept in dire cirumcstances and even then, two keys and special codes should be provided).
If I'm remembering my Crockford correctly, you'll want to put var in front of the two inner functions, otherwise they will be implicit globals. If you want them to be globals, then that's moot. Either way, your second inner function declaration should probably end in a semicolon. This might be a misformating thing, but I think its generally accepted that the bodies of functions are indented one more level in. Also, I've never seen the (function()){/* stuff */}(); construction before, but that says pretty much nothing.
I'd write it these ways - one for if your just declaring a function and another for if your using an anonymous function and immediately applying it to get a result, because I don't which one you're trying to do (again, if you want the inner functions to be global, then this won't be what you intended):
//function declaration
var myFunction = function () {
var _blah = 1;
var someFunction () {
alert(_blah); //or console.log(_blah); for debugging purposes
};
var someOtherFunction () {
someFunction();
};
};
//using a one-of to assign a result
/* NOTE: if you are using this version, myResult will be undefined
(at least given the functions you provided), but like I said,
I don't recognize the construction you provided, and am therefore
assuming that you meant one of these two, which could be a perfectly
falacious assumption, and in that case, my apologies
*/
var myResult = function () {
var _blah = 1;
var someFunction () {
alert(_blah);
};
var someOtherFunction () {
someFunction();
};
}();
BTW, (and I don't want to overstep) Crockford's "JavaScript: The Good Parts" is a stellar reference for JavaScript syntax. He also has, on his website a JavaScript style guide of sorts (though I don't know how widely followed it is). Link is: http://javascript.crockford.com/code.html
I also use the "_" in c# for private/protected members. It is a fast way to see if the variable is a member-variable or not. And you can access it faster with code-completion because you don't get in mess with the public members (private: _blah , public property: Blah).
But are there any private members in javascript anyway? I think every variable defined as member is accessible from the outside.
So you don't have a public wrapper for the private member. And that means the "_" is a bit a overhead and the same can be achieved with "this.".
I prefer you to use the following stuffs which is preferably used around the world programmers.. see below
i = Int
f = Float
o = Object
r = Return
a = Array
e = Element
g = Global declaration
hook = a function which can be used for hooking with other functions
call = a function which can be used for making call from client to server system
sync = a function which can be used for SYNC
and so on.. you can prefix on your coding...

Categories

Resources