this versus function property in javascript - javascript

I want to create a static variable in my js. From what I know with my little js knowledge is, I can do it using this two ways.
function foo (){
if (this.counter==undefined){this.counter=1}
else {this.counter++ } ;
}
function foo (){
if (foo.counter==undefined){foo.counter=1}
else {foo.counter++ } ;
}
Are these two things essentially the same or I need to to careful in selecting one versus other.
Another question I have is: why var is not needed when doing these?

No, they are not equivalent. In your first example, you are using this. this can actually change depending on how the function is being called.
function showThis(){
console.log(this);
}
var obj = { };
obj.showThis = showThis;
showThis(); // gives 'window', or the top-most scope of your page
obj.showThis(); // gives obj as 'this'
If you are always calling the function the same way, then this would just mean the value counter is tracked as a property on window.counter. This is bad, because you may accidentally have an actual variable named counter in that scope, that you are now using in a different way somewhere else. If you are not calling it the same way everytime, then this will be different and probably not giving you your desired behavior.
If you are trying to keep a count on the number of times foo is being called, independent of how/who is calling it, then your second approach is more appropriate. For the sake of code clarify/convention, I would write it this way:
function foo (){
// If counter does not exist, create it and initialize it to 0.
foo.counter = foo.counter || 0;
foo.counter++;
}
foo.counter; // undefined, since foo has never been called yet
foo();
foo.counter; // is now 1

var is used to create a variable in the current scope.
Both the approaches you are taking are setting a property on an object that exists in a wider scope.

Related

declaring local variables inside document ready or inside function in different scope

I need to know which is the better way of declaring some local variables. Which is better in terms of practice, performance? Since, local variables declared inside the function gets removed as soon as the function is executed, does declaring as many local variables (eg: a,b in example below) inside various functions compared to declaring only once inside document.ready() makes any difference?
Method 1:
<script type="text/javascript">
$(function() {
getItem1();
getItem2();
}
function getItem1() {
var a = 100;
var b = 1000;
//do something with a,b
return item1;
}
function getItem2(){
var a = 100;
var b = 1000;
//do something with a,b
return item2;
}
</script>
Method 2:
<script>
$(function() {
var a = 100;
var b = 1000;
getItem1(a,b);
getItem2(a,b);
}
function getItem1(a,b) {
//do something with a,b
return item1;
}
function getItem2(a,b) {
//do something with a,b
return item2;
}
</script>
It's really an idea of why i am using these functions and what are my purposes because it may vary, in Method 1 you are declaring the variable inside a function which those variable will be saved in memory as soon as the function is being executed and they will be deleted when it finish , so if the function contain too many variables and too many lines of code it will not be a good idea if you r looking for performance so it is better using Method 2 ,but if your function is easy and having few lines of code with easy execution method 1 is better of course
It's all a matter of what you need, really.
Will you be reusing your functions on multiple instances? Will it be true that if a and b will be supplied on all possible scenarios, the code inside getItem will process the values correctly? If so, then passing the values will be a good choice since you have the free will to pass whatever you want to. If a and b are just constant and will never change at all, then having the values constant would be a great idea as well.
The second choice gives a lot of flexibility and you can change the values anytime you want, this makes the code more 'generic' and 'reusable' - provided you're going to use the same process.
Performance wise, they make a little difference. With the first option allocating a bit more memory since you have to instantiate a and b twice.

javascript - help me understand this structure (lexical scoping)

Below is simplification of some code I am trying to understand.
What are we trying to do in this javascript fragment? It seems we are creating object(?) called myCompany if not already created, then adding child object myProject to myCompany.
Then creating a local variable withinmyCompany.myProject and another local to function myCompany.myProject.myfunction. The () at the end make it execute immediately. And we are doing this to keep localVariable_1 out of global space?
var myCompany= myCompany || {};
if (!myCompany.myProject) {
myCompany.myProject = {};
}
myCompany.myProject = function () {
var localVariable_1;
function myFunction(){
var anotherlocalVariable;
// .. do some stuff
}
}();
The first line checks if the object exists, if not use shorthand definition {} to create an Object. || compares. If argument one is null set argument two.
The if on the next line checks if the property myProject isn't set on the object. ! is the operator. If myCompany.myProject returns undefined this if clause returns true. When true create object as property myProject.
Third part: myProject gets replaced by a function object. This function is defined between { and }, but is immediately called upon by the () behind the function declaration.
localvariable_1 will never be in the global scope since it has the var statement. Binding it to the scope of myCompany.myProject function. Maybe this function is directly called to set up some initial values, but wrap them in a function that could be reused to change the values at another moment.
One piece at a time...
var myCompany= myCompany || {};
if myCompany exists you set it to it, otherwise you create an empty object and set myCompany to an empty object.
NOTE: if myCompany already exists you have no indicator of what it is
if (!myCompany.myProject) {
myCompany.myProject = {};
}
Now that you know myCompany is an object you verify it has a project property on it. if not you set myProject to an empty object.
NOTE: you have tested nothing about myProject so again there is no indicator of what it is
myCompany.myProject = function () {
var localVariable_1;
function myFunction(){
var anotherlocalVariable;
// .. do some stuff
}
}();
Here you are assigning myCompany.myProject. Notice at the bottom the () before the ; That makes this function get executed immediately. Inside of the function you are creating another function that currently isn't doing anything. Where you aren't returning from the function I think it will set myProject to undefined.
You may already know what an immediate function is but if not it is basically a function that is called right away. It is also standard to wrap it in a () so that it is easier to read for example
var someFunction = (function () {
/*whatever*/
} ());
You said this was simplified from the original so I am guessing you removed an important part of the code that actually does things but the confusion is probably due to the JavaScript's way of scoping. It uses what is called Lexical scoping. You can think of it as scoping by functions.
Another thing that may be tripping you up is how JavaScript uses truthy evaluation for logical comparisons.
The last thing to mention that might be confusing the way you read the code is javascript's hoisting.
Hopefully that helps or at least points you to a few things you can look into to figure out the parts you don't exactly understand.
Sorry I just hate writing in comments lol.
If you are trying to help prevent your global scope from getting polluted then you might want to use objects and a something similar to what you are doing. Depending on how crazy you want to get you could look into Prototypical Inheritance.
A common pattern is to do something like this
var company = (function() {
var name;
var getName = function() {
return name;
};
var setName = function(n) {
name = n;
};
return {
getName : getName,
setName : setName
}
}())
Now you can do company.setName("yoda") or whatever.
This will give you a basic getter and setter where no one can change the companies name without going through your getter and setter and it also doesn't pollute the global scope. You can have whatever you want on company this way and you also encapsulate the data within the object.
Notice how var company = a function that is called immediately which returns an object that has whatever you want to encapsulate on it.
Is that what you are talking about?

Javascript defining functions

I've been learning Javascript with Khan Academy. I'm looking at : http://www.khanacademy.org/cs/speed-circles/964929070
there is a line that reads "var draw = function() {...}" is he defining a function called draw? Or is the variable draw calling some function (which I don't see defined)?
Thanks!
Yes, a function expression is being assigned to the variable named draw. You can even call it:
var draw = function() {
console.log('xyz');
};
draw(); // 'xyz'
In JavaScript, functions are objects, just like arrays and -logically- objects are. As you may have found out already these objects can be assigned to a multitude of variables, but as soon as you change one of these variables, they all change. That's because JS always assigns by value, but a variable is never assigned an object directly: it's assigned a reference to an object:
var obj = {iam: 'an object'};
var reassign = obj;
console.log(obj);//shows object
console.log(reassign);//surprize, shows the same thing
reassign.bar = 'foobar';
console.log(obj.bar);//logs foobar, the variable obj has gained the same property, because it is the same object.
The same applies to functions, being objects, the can be assigned to variables/properties all over the place, but it'll still be the same object/function:
var foo = function()
{
console.log('I am an object');
};
var second = foo;
second();//logs I am an object
console.log(second === foo);//logs true, because they both reference the same thing
Why, then, you might ask is an anonymous function being assigned to a variable, instead of just declaring a function as you'd expect? Well:
function foo(){}
is hoisted, prior to running any code, JS moves all function declarations and variable declarations to the very top of the scope, but in your case, you're not simply defining a function, or declaring a variable: JS has to do something, too: assign a reference to a variable. The function won't be hoisted:
var foo = function()
{
console.log('foo');
};
foo();//logs foo
foo = function()
{
console.log('bar');
};
foo();//logs bar now
If foo were undefined prior to the assignment, you'd get an error. If any code preceded the code above, JS would hoist the variable declaration of foo, but it's value would still be undefined.
What's the point? This will prove useful when you start playing with closures, or if you need the function to differ, depending on a branch (if (x){ foo = functionX} else { foo = functionY;}). These are just 2 reasons why you'd want to avoid scope hoisting... but the most important reason of all ATM has to be redefining a function on the fly
Note that in processing.js (as used by this Khan academy demo), the function draw is automatically called every frame reference doc.
This bit of code overrides the default (empty) implementation of draw so that the given code is called every frame.
Khan academy has a tutorial about this use of the draw function here.
function draw(){ return "Sample"; };
var draw = function(){ return "Sample"; };
are same meaning.
function () { ... } creates a function value. That is, something that can be passed around just as easily as a number, or any other object in javascript.
He then binds it to the name draw for future reference.
He could as well have written
function draw() {
...
}
For these purposes they are equivalent.

Why can I reference a variable not yet defined in Javascript?

When creating the function foo here, I reference a variable fromTheFuture the hasn't been declared yet. This actually works as expected, but why? Is it considered dangerous or bad practice?
var foo = function(x) {
return fromTheFuture * x;
};
var fromTheFuture = 5;
console.log(foo(10));
I can see this being very convenient though, if you have several functions that wants use each other in a cycle fashion - without having to declare them all with var in the beginning of the method.
By the time foo is called, fromTheFuture is defined. More accurately, due to hoisting, your code is essentially:
var foo, fromTheFuture;
foo = function(x) {return fromTheFuture*x;};
fromTheFuture = 5;
console.log(foo(10));
If you were to call foo(10) before fromTheFuture=5, you would get NaN.
Yes, the entire script is processed first, the variables added to the "data store" and only then the execution is performed.
However, this is not encouraged as it makes the code hard to read. If you want to know more about javascript code quality, check out jslint. It's a sort of FxCop for js. Try copy-pasting your code in there.
the reasone behined it in javascript it define all varible first and then start initializing and then after if somewhere it need its intialization point it try intializized called one first

How to create Semaphore between HTML elements loaded async

I have in an HTML page, an element that appears several times, and running the same JS.
Problem is, I want it to do a specific function only if it was the first one to run it (his siblings never ran it - YET).
I need semaphore to sync between them.
I am unable to know how to declare a variable and to do semaphore in this way in JS.
There are lots of approaches.
You need to put a flag somewhere. In the absence of anything else, you can put it on window, but use a name that's unlikely to conflict with anything else.
Then the JavaScript is quite straightforward:
if (!window.myUniqueNameFlag) {
window.myUniqueNameFlag = true;
// Do your processing
}
But again, putting things on window is not ideal if you can avoid it, although it's very common practice. (Any variable you declare at global scope with var¹ is a property of window, as is any function you declare at global scope.)
If your function is already declared at global scope (and therefore already occupying a global identifer / window property), you can do this to avoid creating a second identifer. Instead of:
function foo() {
// ...your processing...
}
Do this:
var foo = (function() {
var flag = false;
function foo() {
if (!flag) {
flag = true;
// ...your processing...
}
}
return foo;
})();
That looks complicated, but it's not really: It defines and immediately invokes an anonymous function, within which it defines a variable and a nested function, then it returns the nested function's reference and assigns it to the foo variable. You can call foo and you'll get the nested function. The nested function has an enduring reference to the flag variable because it's a closure over the variable, but no one else can see it. It's completely private.
A third option is to just use a flag on the function object itself:
function foo() {
if (!foo.flag) {
foo.flag = true;
// ...do your processing...
}
}
Functions are just objects with the ability to be called, so you can add properties to them.
¹ Variables declared at global scope with let or const are globals, but do not become properties of window.

Categories

Resources