Is there a difference between Object.list = {} and list = {}? - javascript

I really wonder if there is a difference other than making the code more structured between Object.list = {} and list = {}?
Example:
var Player = function(){
}
Player.list = {};
var list = {};

Player.list defines list within the Player function. As such, it only has scope within that function, and cannot be used outside of the function (without explicitly stating that it's a global). Conversely, var list allows you to use list globally by default.

When you declare a variable as below:
var list = {};
the variable is created on the window global object and it is equivalent to following code:
window.list = {};
The problem with it is there could be couple JavaScript files on the page that contain the same variable defined in two or more places, which creates name clashing issue. To avoid that scenario you can declare your own name space and define a new variable there
var Player = function(){
}
Player.list = {};

Related

how to invoke a dynamically named object and its method in javascript?

I have a situation in which the name of my object will be dynamic..
i.e.
txtGrantAccess_5.GetValue();
i want to know how can I call this dynamically?
e.g.
var abcd = 'txtGrantAccess_5';
abcd.GetValue();
Please note that txtGrantAccess_5 already exists, please can you also avoid the usage of eval in your answer? I have tried understanding other questions almost similar to this but they are not the same thing...
You cannot get local variables dynamically. However, if it's a property of an object you can get it with the [] syntax.
var obj = {};
obj.foo = function() {};
obj.foo();
obj['foo'](); // same as above.
But in this case a local variable cannot be fetched dynamically at all.
var fn = function() {
var foo = '123';
// no way to get foo dynamically.
}
One exception is global variables. In the global scope, local variables are created as properties of the window object:
// global scope, outside of any function.
var foo = function() {};
window.foo();
window['foo'](); // same as above
Just keep in mind that lots of global variables are usually frowned upon, espcially if there is enough that you need to find dynamically like this. You probably just want a container object to keep these values in, like the first example I posted.
Try this snippet
var abcd = 'txtGrantAccess_5';
this[abcd].GetValue();
but be careful with value of "this". If it's in a browser maybe this will help
var abcd = 'txtGrantAccess_5';
window[abcd].GetValue();
How about:
var container = {};
var name = 'dynamicName';
container[name] = new MyObject();
container[name].getValue()

Why can't I use var when declaring sub name spaces?

Why does the following work
var NameSpace = NameSpace || {};
NameSpace.Foo = 2;
But this does not?
var NameSpace = NameSpace || {};
var NameSpace.Foo = 2;
Any insight into the inner workings of the variable deceleration in regards to namespaces would be appreciated.
JavaScript does not have namespaces. Your first line of code is declaring a variable whose name is Namespace, and whose value is an object:
var NameSpace = NameSpace || {};
Then you create a property Foo on the object, and assign a value to it:
NameSpace.Foo = 2;
Bottom line: variables and object properties are different things (among other differences, variables have scope, while properties don't). The var statement is only for declaring variables.
var foo = foo;
works because ECMAscript will decouple this line in away like
var foo;
foo = foo;
under the hood. This concept is commonly called hoisting.
Your second snippet can't work, since we are assigning an object property. The var keyword always implies, that we want to create a variable, a symbol so to speak, within the current Execution Context.
What you could do of course, is
var Foo = NameSpace.Foo = 2;
This would
create the variable Foo in the current context
assign the object property Foo on the NameSpace object
assign both the value of 2
var is reserved for declaring new variables, not modifying existing ones.
Additionally . is an invalid character for a variable name.

create new javascript object from variable

i would like to create a new object in javascript (using simple inheritance) such that the class of the object is defined from a variable:
var class = 'Person';
var inst = new class
any ideas?
You can do something like
function Person(){};
var name = 'Person';
var inst = new this[name]
The key is just referencing the object that owns the function that's the constructor. This works fine in global scope but if you're dumping the code inside of a function, you might have to change the reference because this probably wont work.
EDIT: To pass parameters:
function Person(name){alert(name)};
var name = 'Person';
var inst = new this[name]('john')
Here's how I do it. Similar to meder's answer.
var className = 'Person'
// here's the trick: get a reference to the class object itself
// (I've assumed the class is defined in global scope)
var myclass = window[className];
// now you have a reference to the object, the new keyword will work:
var inst = new myclass('params','if','you','need','them');
To improve on the answer above by meder:
To invoke using a function:
You would simply replace 'this' with the scope containing the class you are referring to, for example if the class is written in the global scope like below:
function Person(name){alert(name)};
var name = 'Person';
function classMaker(){
var inst = new window[name]('john');
}
classMaker();
To put it more plainly, you can use new on a variable that references a class:
class Person{}
const class_type = Person;
const instance = new class_type();
console.log("works?", instance instanceof Person); // true
I had a similar problem in Node.js, when I had to dynamically create different handler objects depending on the data. First I gathered all available handlers, which were implemented as separate modules, in an object. In a simple case this could be hardcoded like this.
var handlers = {
handlerX : require('HandlerX'),
handlerY : require('HandlerY')
};
Then, whenever I had to instantiate a handler, I did it like this:
var handlername = getHandlerName()
var handler = new handlers[handlername]();
Of course this only works if you know, or can programmatically determine the list of all objects you will need to create.
This talk was really helpful when I got into different inheritance patterns in javascript. Example code is included in the second link (the video introduces it).
http://alexsexton.com/?p=94
http://alexsexton.com/inheritance/demo/
http://alexsexton.com/?p=51

Json2: why does "var JSON" in global scope not clobber the global JSON object?

At the top of json2.js (line 160 after the comments: https://github.com/douglascrockford/JSON-js/blob/master/json2.js), is the following code:
var JSON;
if (!JSON) {
JSON = {};
}
Typically, declaring var something will set "something" to undefined:
var something = {};
(function(){
var something;
console.log(something); // logs undefined
})();
Normally I would accomplish this goal by using:
var JSON = JSON || {};
So what's with the global JSON object that allows writing "var JSON" to not set it to undefined?
And why on earth would someone like Crockford promote a technique, that, in any other situation, would NOT operate like this?
It does this with any variable. Declaring it in the same scope again won't reset the value of the variable. I imagine it's a result of variable hoisting (all declarations are moved to the top of the function).
var a = 2;
var a;
console.log(a) // 2
In this specific case
var JSON;
if (!JSON) {
JSON = {};
}
and
var JSON = JSON || {};
are pretty much equivalent. It's just a matter of style preferences.
Now, if he had put it inside the self executing anonymous function, the local JSON would be set to undefined.
If you're asking why he's doing that, it's because he doesn't want to overwrite the native JSON object if it exists, but I think you knew that already.

creating an object and initializing an object - Difference

////Creating Object
var Obj;
// init Object
Obj= {};
What's the difference between these
two?
Is it possible to make it into a
single line?
Any Advantages of using like this?
the first declares a variable in the current scope, it does not assign any value to it,thus it is not creating any object, while the second one creates an empty object literal to which you can refer through the global Obj variable.
There are 2 main differences : scoping variables and initializing vs declaring.
ex :
var Obj;
alert(typeof Obj);//='undefined'
//scoping :
function foo(){
obj1 = {};
var obj2 = {};
}
alert(typeof obj1);//='object'
alert(typeof obj2);//='undefined'
// obj2 is visible only in the foo function scope,while
// obj1 is being attached to the global scope, the window object
// you can access obj1 as window.obj1 too
var Obj; is not creating an object, it is declaring the variable Obj.
Obj = {}; is initializing the variable Obj with an empty object.
Of course you can combine it and do it in one go:
var Obj = {};
You basically just have to separate declaration and initialization, if you want to initialize the variable with different values, based on some condition or if the variable should be declared in another scope. For example:
var Obj;
if(something) {
Obj = 'me';
else {
Obj = 'you';
}
var Obj; does not create an object, it declares a variable.
Obj = {}; assigns an empty object to the variable named Obj. If Obj was not previously declared, this implicitly declares the variable in the global scope, since the var keyword is missing (don't do this).
var Obj;
only declares the Obj variable, whereas
var Obj = {};
declares and initializes the Obj variable as an empty object.
Make sure you understand the use of the var keyword here as well. It can be used in declaring and/or initializing variables. The difference between
Obj = {};
and
var Obj = {};
is that the var-less code initializes Obj in the global namespace (often considered a bad practice).
tl;dr: In most cases, it is best to initialize and declare at the same time in the local scope, using the var keyword:
var Obj = {};
Maybe I'm not totally understanding your question, but...
var Obj= {};
Is totally fine.
The first allocates the slot for the variable Obj but leaves it undefined. The second binds a newly created object to the name Obj.
You can do it in one line: var Obj = {};. Doing it in two steps has no real advantages, only risks.
var Obj;
this is not creating an object. it defines a variable;
object is first created and than initialized so this are two key processes that are both necessary to have an object.
This line does not actually create an object. Rather it creates a variable (or a place that could hold an object if you put one in there).
var Obj;
This line, does create an object, and places it into the variable.
Obj = {};
This line "initializes" the object by creating a property and setting it to something.
Obj.Something = null;
Note that by saying
var Obj;
you are not creating the object, merely defining a (in scope of a function local) variable initially set to null
Other than that there's no difference whether you merge it into one statement or not.
If that's all the code you've got, there is absolutely NO difference between this:
var Obj;
Obj = {};
and this:
var Obj = {};
IF that's all the code you've got, with nothing in between modifying the Obj variable. In fact, I'd argue that the second way of doing it would be faster than the two lines above.

Categories