In javascript, what is the difference between an object and a namespace? - javascript

While reading "Object-Oriented JavaScript" on Mozilla's website, I stumbled upon this note:
It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
However, the note is not clear about what is meant by "language-level difference".
Does it mean there are two ways of writing the same thing?
Or that there are two terms that refer to the same thing?

You've taken the quote out of context. The answer is in the paragraph above the quote:
A namespace is a container which allows developers to bundle up functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties, and objects.
(Emphasis mine)
The quote:
It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
Is just saying that this means a "namespace" is just a object used as a "namespace".
There are no "real" namespaces in JS.

Some languages have an actual namespace which is not the same thing as an object. JavaScript is not one of those languages, so objects are used for this purpose.
For example, the Math functions like Math.round and Math.abs, are all namespaced in the Math object. They aren't really contextual methods like toString is (at least not in any implementation I've found), just collected under an object to keep it organized. *
* They are technically methods, because they are accessible by a property on an object (a definition that technically makes all global functions methods because they are available through the global object (ie. window.Function())), but unlike methods like toString, or the methods of most console implementations like console.log they do not depend on the object they are called on and the this value is irrelevant. The Math object is used purely for namespacing, not because of the context it gives.

First, are you sure you know what a namespace is? Real Quick:
Let's use an analogy. On your computer you have files. But you don't just have files you have folders. Why?
Because if there were no folder every file name would have to be unique and it would be hard to keep things organized.
Same for variables names if you only had global variables. If you could only have global variables every variable name would have to be completely unique.
This would be very difficult to keep track of. Chances are you would probably end up using the same variable name by accident. Your code would act funny and it would be very difficult to track down the problem.
So what's the solution?
That's right put your variables into folders, ahem, sorry, I meant namespaces, put them into namespaces. I gotta figure out how to use the backspace key.
Anyway, languages like C# and Java let you do exactly this:
// C# - example of a language with built in support for namespaces
namespace MySpace {
class MyClass {
}
}
namespace Facebook {
class MyClass {
}
}
There no conflict because the classes are in different namespaces. Then in your code if you wanted to instantiate them you would write something like this:
// C# again (JavaScript code coming up soon - keep scrolling)
var myObject = new Facebook.MyClass();
That's great but JavaScript doesn't have a namespace keyword. Technically it doesn't have namespaces, what it does have is some really clever programmers.
Their solution? Use objects.
// JavaScript
var MySpace = {};
MySpace.MyFunction = function() {
// insert brilliant code here
};
var Facebook = {};
Facebook.MyFunction = function() {
// insert more brilliant code here
};
Now you have 2 functions with the "same" name that don't get in the way of each other. If you want to call the Facebook version of MyFunction you would write code like this:
// JavaScript
Facebook.MyFunction();
As you can see in these examples MySpace and Facebook are really objects, but they are objects that we are using only to separate functions and variables, which means we're using them for nothing more than to serve as namespaces.
One Extra Note
A lot of times you will see "namespace" objects declared like this:
var MySpace = MySpace || {};
This means MySpace = MySpace if the MySpace object already exists. Otherwise it's assigned a new empty object. This is a way of reusing the MySpace object/namespace in multiple files.
Each file adds it's own functions and variables to the same "namespace" object. For example:
var MySpace = MySpace || {};
MySpace.a = 10;
var MySpace = MySpace || {};
MySpace.b = 20;
You end up with one MySpace object with the variables a and b. This is true even if the code were in different files and even if you reverse the order.

It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
It's saying that a "namespace" is not an actual type of component in JavaScript, but rather just another use of a plain old JavaScript object.

Related

Why javascript function has instance per call?

The javascript introduction says:
When I have code like below:
var Person=function(name){
this.name=name;
this.sayHello=function(){return 'Hello '+name;}
}
Whenever I instantiate a "Person", there will be a copy of "sayHello" function in the memory. To reduce this memory consumption, I can change the code like below:
var Person=(function(){
var sayHello=function(){return 'Hello '+name}
return function(name){
this.name=name
this.sayHello=sayHello
}
})()
In this way, there'll not be multiple copies of sayHello()
My questions are:
For the 1st type of code, what's the benefit except wasting more memory?
Should we write code in the 2nd way, or javascript should avoid one copy for one function per instance?
Thanks a lot.
The behavior you are witnessing is the result of two things:
Functions as first-class objects. This means functions are treated the same way as strings, numbers, arrays etc.
How local variables are treated in functions. Local variables are created (typically on the stack) each time the function is called. This allows functions to be called recursively.
This behavior exists in many different languages that have anonymous functions like Go, Perl, Lisp etc.
The two rules above means that each time you call your function the inner function gets created and assigned to the variable.
What's the advantage of this?
The primary advantage of this from the language point of view is consistency of behavior. It means functions are really treated as first-class objects just like numbers, strings etc. Treating it consistently means that people who try to use anonymous functions won't get surprised by the behavior.
How do people use this feature?
Sometimes you find yourself writing several different functions that look similar:
function double (x) {return x * 2};
function quadruple (x) {return x * 4};
Wouldn't it be nice to be able to categorize a "family" of functions that are similar and somehow write them once?
Well, in languages like C you may use a macro system to basically cut-and-paste the text you type to generate several different code.
In languages with first-class-functions you write a function to generate functions:
function makeMultiplier (factor) {
return function (x) { return x * factor }
}
So now you can do:
var double = makeMultiplier(2);
var quadruple = makeMultiplier(4);
Now OBVIOUSLY for this to work the makeMultiplier() function MUST return two different functions. It cannot just modify a single function to do different things each time it is called. Otherwise both the double() and quadruple() functions will multiply by 4 after the second call to makeMultiplier().
Implementation detail
It is possible to create a system whereby the body of inner functions are compiled only once and the differences are captured by a closure. So all functions only occupy RAM once but different versions of a function may occupy more than one closure. It is possible that this is how it's implemented by most js engines but I don't really know. If so, then inner functions do take up additional RAM each time they're defined but not by much (typically by one stack frame - so each function definition takes up the same space as a function call).
From the programmer's point of view though, inner functions must appear to work as if they're created each call because that's how you'd expect them to work.
For the 1st type of code, what's the benefit except wasting more memory?
The only time i'd use something like this is for quick testing of an anonymous object. An example of this would be in some sort of factory implementation:
getWidget = function(){
return {
foo: 'bar',
test: function(){ ... }
}
}
And honestly, this would be quickly replaced with proper coding conventions after I confirmed my initial testing.
Should we write code in the 2nd way, or javascript should avoid one copy for one function per instance?
I'd say no. Don't write code like this. It's unnecessarily convoluted and doesn't appear to work from what I can tell. I'd recommend just creating methods on the function prototype:
var Person = function(name){
this.name = name;
}
Person.prototype.sayHello = function(){
return 'Hello ' + this.name;
}
pros
- easy to read
- easy to manage
- this is scoped properly within the context of calling methods
cons
- a nominal increase in effort to code
- per a comment to the question, you lose access to variables scoped exclusively to the constructor
For the 1st type of code, what's the benefit except wasting more memory?
This could be used for access control (like private in some other languages).
Consider:
var Person=function(name){
this.sayHello = function(){return 'Hello '+name;}
};
name can only be accessed by sayHello, which is a opaque Function.
Other code may replace this.sayHello, but will not be able to let this sayHello instance use another name.

What is difference between function FunctionName(){} and object.FunctionName = function(){}

Today while working my mind was stack at some point in javascript.
I want to know that what is basic difference between
function FunctionName(){
//Code goes here;
}
And
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
//Code goes here;
}
Both are working same. Then what is difference between then. Is there any advantage to use function with object name?
I have read Question. But it uses variable and assign function specific variable. I want to create object and assign multiple function in single object.
The first one defines a global function name. If you load two libraries, and they both try to define FunctionName, they'll conflict with each other. You'll only get the one that was defined last.
The second one just has a single global variable, MyFuncCollection. All the functions are defined as properties within that variable. So if you have two collections that try to define the same function name, one will be FuncCollection1.FunctionName, the other will be FuncCollection2.FunctionName, and there won't be any conflict.
The only conflict would be if two collections both tried to use the same name for the collection itself, which is less likely. But this isn't totally unheard of: there are a few libraries that try to use $ as their main identifier. jQuery is the most prominent, and it provides jQuery.noConflict() to remove its $ binding and revert to the previous binding.
The short answer is, the method in object context uses the Parent Objects Context, while the "global" function has its own object context.
The long answer involves the general object-oriented approach of JavaScript, though everything in JavaScript is an object you may also create arrays with this Method.
I can't really tell you why, but in my experience the best function definition is neither of the top mentioned, but:
var myFunction = function(){};
It is possible to assign function to variables, and you may even write a definition like this:
MyObject.myMethod = function(){};
For further reading there are various online Textbooks which can give you more and deeper Information about this topic.
One main advantage I always find is cleaner code with less chance of overwriting functions. However it is much more than that.
Your scope changes completely inside the object. Consider the following code ::
Function:
function FunctionName(){
return this;
}
FunctionName()
Returns:
Window {top: Window, location: Location, document: document, window: Window, external: Object…}
Object:
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
return this;
}
MyFuncCollection.FunctionName()
Returns:
Object {}
This leads to some nice ability to daisy chain functions, amongst other things.
The first:
function functionName (){
//Code goes here;
}
Is a function declaration. It defines a function object in the context it's written in.
Notice: this doesn't have to be the global context and it doesn't say anything about the value of this inside it when it's invoked. More about scopes in JavaScript.
Second note: in most style guides functions are declared with a capitalized name only if it's a constructor.
The second:
var myFuncCollection = {};
myFuncCollection.functionName = function () {
//Code goes here;
};
notice: don't use the new Object() syntax, it's considered bad practice to use new with anything other then function constructors. Use the literal form instead (as above).
Is a simple assignment of a function expression to a property of an Object.
Again the same notice should be stated: this says nothing about the value of this when it's invoked.
this in JavaScript is given a value when the function object is invoked, see here for details.
Of course, placing a function on an Object help avoiding naming collisions with other variables/function declarations in the same context, but this could be a local context of a function, and not necessarily the global context.
Other then these differences, from the language point of view, there's no difference whatsoever about using a bunch of function declarations or an Object with bunch of methods on it.
From a design point of view, putting methods on an Object allows you to group and/or encapsulate logic to a specific object that should contain it. This is the part of the meaning of the Object Oriented Programming paradigm.
It's also good to do that when you wish to export or simply pass all these functions to another separate module.
And that's about it (:

Accessing variables from another CoffeeScript file?

What is best practice to get a variable outside of its anonymous function without polluting the global namespace?
A number of possibilities:
Create a properly name-scoped public accessor function to obtain the value upon demand.
Pass the value to the functions where it will be needed
Pass a private accessor function to the other module
Put the variable in a properly name-scoped global
Pass a "data object" to the other module that has the value in it (along with other values)
Which makes the most sense depends upon how much data you need to share, how widely it needs to be shared, whether the sharing is both ways, etc...
The typical design pattern for exposing global data with the minimum impact on polluting the global namespace is to do something like this:
var JF = JF || {}; // create single global object (if it doesn't already exist)
JF.getMyData = function() {return(xxx);}; // define accessor function
JF.myPublicData = ...;
Then, anywhere in your app, you can call JF.getMyData(); or access JF.myPublicData.
The idea here is that all public methods (or even data objects) can be hung off the JF object so there's only one new item in the global space. Everything else is inside that one object.
There have been several CoffeeScript questions along these lines:
How do I define global variables in CoffeeScript?
Expose a javascript api with coffeescript
Getting rid of CoffeeScript's closure wrapper
as well as several others that are environment-specific. If you posted a more detailed question with a concrete example, I could provide a more specific answer.

Help understanding twitters widget.js file, a closure within a closure?

http://a2.twimg.com/a/1302724321/javascripts/widgets/widget.js?1302801865
It is setup like this at a high level:
public namespace:
TWTR = window.TWTR || {};
Then a closure:
(function() {
...
})(); // #end application closure
Within the application closure:
TWTR.Widget = function(opts) {
this.init(opts);
};
(function() {
// Internal Namespace.
var twttr = {};
})();
Some methods are marked public, others private, and the only difference seems to be the naming convention (private starts with underscore '_').
Is it designed using the module pattern?
Why or what benefit do you get with a closure within a closure?
Since they load the widget.js before jquery, this means widget is designed to run w/o jquery since order matters correct?
Just trying to learn from this thing!
It is setup like this at a high level:
public namespace:
TWTR = window.TWTR || {};
That is bad coding practice, variables should always be declared with var. And there are no "namespaces" in javascript, that term is applied to the above construct but it isn't really appropriate. Better to say its methods are contained by an object.
Then a closure:
> (function() { ...
>
> })(); // #end application closure
That pattern has come to be called an immediately invoked function expression or iife. Not sure I like the name, but there you go. Anyway, it doesn't necessarily create any useful closures. A closure is only useful if a function creates variables that become bound to some other execution context that survives beyond the life of the function that created them (I hope that doesn't read like gobbledy-goop). You don't need an iife to create a closure.
However, you can use the above pattern to create closures since it's a function much like any other function.
Within the application closure:
> TWTR.Widget = function(opts) {
> this.init(opts); }; (function() {
> // Internal Namespace.
> var twttr = {}; })();
Some methods are marked public, others
private, and the only difference seems
to be the naming convention (private
starts with underscore '_').
The use of "public" and "private" are a bit misleading in javascript. The use of underscore to start identifer names indicates something that should only be used within the current scope, or by the "library" code itself. It's a bit redundant since the code should have a published API and any method that isn't part of the API shouldn't be avaialble externally.
But that is largely a matter of coding style and personal preference.
Is it designed using the module pattern?
Richard Cornford's "module pattern" is just that, a pattern. It's handy for simulating "private" variables in javascript, and also to share properties between functions or methods other than by the usual prototype inheritance. widget.js might be implemented (in parts) using the module pattern, but it it was likely designed by considering requirements and functionality. ;-)
Why or what benefit do you get with a closure within a closure?
Exactly the same benefits of any closure as stated above. Accessing variables essentially by placing them on an appropriate part of the scope chain is essentially the same as accessing properties via a [[prototype]] chain, only with (very different) mechanics - one uses identifier resolution on the scope chain, the other property resolution on the [[prototype]] chain.
Edit
One drawback is that the entire activation object that the closed variable belongs to is probably retained in memory, so if you just need access to a shared variable, better to consider some other scheme, perhaps even classic prototype inheritance. Or at least if you are going to use closures, try to keep the related activation object as small as reasonably possible (e.g. set any variables that aren't used to null just before exiting).
e.g.
var foo = (function() {
// Variables available for closure
var a, b, c;
// Use a, b, c for stuff
...
// Only want closure to c
a = null;
b = null;
return function() {
// use c
}
}());
Since they load the widget.js before jquery, this means widget is designed to run w/o jquery since order matters correct?
I can't access the linked resource right now (corporate blocking of twitter domain), but the load order suggests you are correct. However, some code execution might be delayed until the document is fully loaded so it isn't a guaranteee, you'll need to look at the code.

What is Javascript collision?

Any best practices around it?
JavaScript collision is when you have two global objects with the same name, and one overwrites another. For example, you might reference two libraries that both use a function named $ at the root object (window) for a query function. The idea is that you should use as few global objects as possible. The best way to do this is to create a namespace for any JS you write, just like any other language:
var myApplication = {};
And then add any subsequent functions / objects inside the namespace:
myApplication.init = function () {
}
google sometimes better than stackoverflow
http://javascript.about.com/od/learnmodernjavascript/a/tutorial22.htm
I think it is a concept which detects when two objects collide, this technique is especially useful when creating javascript-based games.
This also refers to collision of different javascript libraries used in one page for example jquery and prototype used in one page and nothing works because of collision usually because of popular $ sign.
Javascript has first class, lexically scoped functions, in other words in side of a function, when you call a variable, it checks itself for an instance of that variable, then checks it's parent function.
<script>
var foo = "test1";
document.write(foo+"\n"); //test1+ a linebreak
(function(){
document.write(foo+"\n"); //test1+ a linebreak
var foo = "test2";
document.write(foo+"\n"); //test2+ a linebreak
})();
document.write(foo+"\n"); //test1+ a linebreak
</script>
I thought it was something that happens when a Mummy Javascript and a Daddy Javascript, who love each other very much want to eval a baby Javascript.
My teacher wasn't very clear on this point however ...

Categories