javascript "static imports" - javascript

Is there anything in javascript that is the equivalent of java static imports? For example, if I have a Math class that looks like
com.example.Math = function() {
function1(...) {}
function2(...) {}
}
Now some of these functions are naturally chained together such that the output to one is the input to another. I can do something like
com.example.Math.function2(com.example.Math.function1());
This is a little ugly looking, and I would really like to do something like:
function2(function1())
But I don't want to put function1 and function2 in the global namespace. Is this possible?

Yes, there is. It's called with.
with (com.example.Math) {
function2(function1());
}
That said:
Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
For example:
var m = com.example.Math;
m.function2(m.function1());

How about:
var Math = com.example.Math;
and then:
Math.fn1( Math.fn2(...) );
I'm assuming of course that your code is not global code. (If you're not familiar with the concept of avoiding global code in JS, read about the module pattern.)
You can go one step further:
var Math = com.example.Math,
func1 = Math.func1,
func2 = Math.func2;
and then:
func1( func2(...) );

I would do something like this:
var O = function() {
var that = {};
var PI = Math.PI;
that.circ = function(r) {
return 2*PI*r;
};
return that;
};
var o = O();
console.log(o.circ(1));
Notice how PI is used without the Math namespace in the O.prototype.circ method.
In JavaScript, there is no distinction between a namespace and an object, so some would argue that Math is not a namespace, but since JavaScript doesn't support the concept, it is as much a namespace as com.mycompany.somelibrary.

One option is to use a closure to wrap the object. It doesn't necessarily eliminate the object itself, but it helps with readability and if you are using a JS compressor can help reduce the output file size:
(function(Math) {
Math.function2(Math.function1(...));
}(com.example.Math);)
You can also pass in multiple objects (ie: function(Math, Foo) {...}(com.example.Math, com.example.Foo)).
If you want to use just a few functions directly, just pass them in like this:
(function(function1, function2) {
function2(function1(...));
}(com.example.Math.function1, com.example.Math.function2);)
This, however, removes the relationship between the Math instance and the functions, so you might get some weird behavior if your methods depend on instance variables. As an example of how that won't work, imagine this class:
com.example.Counter = {
counter: 0,
increment: function() { this.counter++; }
}

Related

JavaScript approach for creating a singleton or keep variable reference

Sometimes techniques like this is used to keep variable reference or create singleton. In this way we will call createVariable one time only.
What are the pros and cons of this approach?
function createVariable() {
// usually here may be some long asynchronous task
//
return true;
}
function useVariable() {
if(!useVariable.someVar) {
useVariable.someVar = createVariable();
}
// do something with useVariable.someVar
}
// we will call useVariable several times.
// The idea is to call createVariable
// one time only.
useVariable();
useVariable();
useVariable();
I am grateful to all ideas and recommendations. I don't want to create a singleton. Just want to keep variable reference on function level. Without
pollute the global scope.
What are the pros and cons of this approach?
The approach is okay, although I question the need for it as higher-level design question.
The implementation has a couple of issues:
If someVar contains a falsey value, you'll recreate it when you shouldn't. To check if you've previously created it, use if(!useVariable.hasOwnProperty("someVar")) { rather than if(!useVariable.someVar) {.
The falsey values are 0, "", NaN, undefined, null, and of course, false. (All other values are "truthy".)
Functions have some built-in properties, both their own (name, length) and ones they get from their prototypes (various methods, mostly). So if your variables have names like name, length, call, and so on, you'll mistakenly think you've created them when you haven't as createVariable will already have those properties with truthy values (in your createVariable case). You can work around that by adding a prefix of some kind, or using a separate object as a map (although objects inherit properties, too, so you'd still probably need a prefix), or if you were using ES2015+, you could use a Map.
You've said you only want to create the variable once and "not pollute the global scope" (which is a good thing to avoid). I do that by just wrapping my code in a scoping function:
(function() {
var someVar = createSomeVar();
// My other code here
})();
That keeps the global namespace untouched, and creates only a single copy of someVar without the need for any particular plumbing.
Here is how you would create a singleton (from http://www.dofactory.com/javascript/singleton-design-pattern):
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
then use it like this
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
//You can see here that they are indeed the same instance
alert("Same instance? " + (instance1 === instance2));
NOTE: this took five seconds to find via Google: http://dofactory.com/javascript/singleton-design-pattern

Best Practices for "Abstract" functions in JavaScript?

I just wrote some JavaScript code that follows along with what I believe to be good practice for creating an object with closure and some functions:
var myStuff = (function() {
var number = 0;
var fn = {};
fn.increment = function() { number++; };
fn.decrement = function() { number--; };
fn.getNumber = function() { return number; };
return fn;
})();
myStuff.increment();
myStuff.increment();
alert(myStuff.getNumber()); // alerts '2'
I have no problem writing code like the previous snippet. I would like to write some code with functionality similar to a OOP "abstract" class. Here is the result of my effort:
var myStuff = (function () {
var number = 0;
var fn = {};
fn.increment = function () { number++; };
fn.decrement = function () { number--; };
fn.doSomethingCrazy = function () { throw new Error('not implemented'); }; // I want to specify later what this does.
fn.doSomethingCrazyTwice = function () { fn.doSomethingCrazy(); fn.doSomethingCrazy(); };
fn.getNumber = function () { return number; };
return fn;
})();
myStuff.doSomethingCrazy = function () { this.increment(); this.increment(); };
myStuff.doSomethingCrazyTwice();
alert(myStuff.getNumber()); // alerts '4'
The above code snippet works, but it doesn't seem graceful. Perhaps I'm trying to force JavaScript (a functional language) to do something it isn't designed to do (object inheritance)
What is a good way to define an object in JavaScript so that a function of that object can be defined later?
Just don't define the function.
Javascript is a duck-typed language. If it looks like a duck and it quacks like a duck, it is a duck.
You don't need to do anything special to make this work; as long as the function exists when you call it, it will work fine.
If you call it on an instance that doesn't have the function, you'll get an error at the callsite.
I agree with SLaks, there's no need to define the function, but I tend to anyway. That's because to me the important part is in the documentation. When somebody reads my class, I want it to be clear that you must implement these methods, what arguments will be passed and what should be returned.
This is from a file at work. There were multiple implementations of a feature with a base class that did the data loading at intervals.
/**
* Called when data is received and should update the data buffer
* for each of the charts
*
* #abstract
* #param {cci.ads.Wave[]} waves
* #void
*/
updateChartsData: function(waves){
throw "Abstract method updateChartsData not implemented";
},
2019 Update
Use TypeScript if you can Declaring abstract method in TypeScript
As our team is growing and our javascript project is getting more complex we have to start implementing OO features as well.
In our javascript 'abstract' method we simply throw an error, or pop up an alert. This is an example from out Page object:
Page.initialLoad = function() { //abstract
alert('Page.initialLoad not implemented');
};
In java world it is analagous to :
public void abstract initialLoad();
The Java code gives a compile time error, however in the Javascript we would get a runtime error. (a dirty error dialog saying that an implementing object hasn't implemented that method yet).
We have a number of disparate teams that use the Page object; the philosophy of 'duck typing' absolutely does not cut it with us. Without these pseudo 'abstract' methods we have a general lack of API communication, and sometimes we get sabotaging of the super object (ie. because a user has no idea they are supposed to implement the method).
I am tired of this 'duck typing' philosophy. I'm not sure if proponents have ever been in a complex Javascript project with 10+ developers.
If you don't find your way graceful there is probably a way to create some functions to stramline the process to make it look better. But back to the topic...
Yes, Javascript has builtin delegation, aka inheritance, via prototypes.
Given a prototypal object:
var proto = {
f: function(){ console.log(this.x); }
}
We can create a new object that inherits from it:
var obj = Object.create(proto);
obj.x = 42;
obj.f(); //should work!
for(var i in obj) console.log(i);
//should print x, f and some other stuff perhaps
Just note, that doing things directly via Object.create is not always supported (old browsers, etc). The old (and some may say, normal) way do do stuff is via the funky new operator (donĀ“t think too much on the name - its confusing on purpose to distract the Java people)
function Constructor(arg){
this.x = arg;
}
Constructor.prototype = {
f: function(){ ... }
};
var obj = new Constructor(17);
obj.f();
An important difference to consider with prototypical inheritance is the lack of private variables. Only public variables can be inherited! Because of this, a common convention is to use underscore as a prefix for private and protected variables.
You might want to take a look at this previous post How do I create an abstract base class in JavaScript?
Just a few sites for some light reading for you on OOP and JavaScript, I am assuming that your new to JavaScript as an OOP langauge based of a comment you said
http://mckoss.com/jscript/object.htm
http://www.codeproject.com/KB/aspnet/JsOOP1.aspx
http://www.javascriptkit.com/javatutors/oopjs.shtml

Empty Function use in Javascript

I am trying to understand a third party Javascript code.
But am not able to figure out what is the use of the below coding style.
function A(){
}
A.Prop = '23';
A.generate = function(n){
// do something
}
And then it is just used as :
A.generate(name);
Can someone explain what this code is doing.
I understand some bit of OO Javascript, but i wonder if this is any other form of extending an object with new properties to it. Though i dont see any "new" keyword being used, to create an object.
Any ideas ?
Thanks,
They are creating a namespace. There are many ways to do this, and all are more-or-less equivalent:
A = {
Prop : '23',
generate : function (n) {
// do something
}
};
Or, equivalently:
A = { };
A.Prop = '23';
A.generate = function (n) {
// do something
};
Also, if you like being verbose:
A = new Object();
A.Prop = '23';
A.generate = function (n) {
// do something
};
function is usually used to denote a "class" rather than a "namespace", like so:
A = (function () {
var propValue = '23'; // class local variable
return {
"Prop" : propValue,
"generate" : function (n) {
// do something
}
};
})();
// then I can use A in the same way as before:
A.generate(name);
It looks like they're using a dummy function to create a namespace.
You're right; this is useless.
They should use a normal object instead.
A function is an object, there's nothing inherently wrong with using it the way it's been used. However, since the function isn't actually used as a function, it would be better to use an Object. You could also use an Array (which is an object), but the same advice applies.
Also, identifiers starting with a capital letter are, by convention, reserved for constructors (unless they are all capitals, which are, by convention, for constants) so use a name starting with a lower-case letter.

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