I am working on angularJs and working on javascript optimization.
I recently saw a video by YUI creator who is a javascript expert about javascript optimization. He explained about variable declaration and scopes and how javascript work. and How javascript engine has to look for variable from current scope till global scope to find it etc etc (Ref: http://jonraasch.com/blog/10-javascript-performance-boosting-tips-from-nicholas-zakas)
My question regarding is (not specific to angularjs) is:
when in my controller i declare a function like:
app.controller('Ctrl', function() {
var func1 = function() {
console.log("Hello");
}
this.func2 = function() {
console.log("World");
}
func1();
this.func2();
});
Which function should be faster ? I know its a overkill but I am interested in knowing how javascript engine works.
in terms of scope these two are identical (they are both local, not global). the difference is in functionality: the "this.func2" function is "public" (you could call that function with a reference to an instance of the Ctrl object), where as the "var func1" is a "private" function.
in terms of the speed of executing a call, I have put together this small test on jspref:
http://jsperf.com/private-vs-public-speed-js
Benchmark.prototype.setup = function() {
var obj = (function() {
this.f1 = function() {
console.log('a');
}
var f2 = function() {
console.log('a')
}
return {
f1: f1,
f2: f2
}
})();
};
comparing between "use public method"
obj.f1();
to
"use private method"
obj.f2(); does not seem to show a significant difference most of the time.
Related
En example can be found in Twitter'a typeahead.js here:
function () {
// ...
return this.each(initialize);
function initialize() {
// ...
}
}
Questions:
What are the scopes and what function sees what?
What is the reason for using such a construct (usage scenarios and advantages)?
Javascript has function based scope, which means that every thing defined inside a function is available from the first line, since the definition is "hoisted" by the complier.
That goes for both variable and function definitions - variable values however, are not available until after assignment.
You can read all about javascript scoping and hoisting here
This means that the function initialize is available from the first line of the wrapping anonymous function.
There is no real reason, and no advantages, for doing it that way, unless you count the code structure as an advantage.
Personally I don't see any reason to do this. For me even it looks a little bit weird. Martin is right. You should be careful, because the defined variables are not accessible like functions. For example this doesn't work:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
var now = function() {
return 10;
}
}
alert(f());
However, this works:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
function now() {
return 10;
}
}
alert(f());
I am currently writing all javascript functionality of a certain page in JQuery's document.ready handler:
$(document).ready(function() {
var one, two, three;
function f1(par1) {}
function f2() {}
...
});
I feel that this isn't optimal or according to Javascript best practices. What I need is a private scope for the page's functionality, nothing needs to be called externally.
I've seen a number of different ways:
jQuery source
(function(window) {
var anObj = {};
...
window.functionality = anObj;
}(window));
A function that is self-invoked with the window as parameter, then setting the functionality object of your application on it.
Codemirror source
window.functionality = (function() {
var functionality = {};
...
return functionality;
}());
Very similar to what jQuery does, but setting the functionality object indirectly on window by making a self-invoking function return something first.
This question
var functionality = {};
(function(obj) { obj.f1 = ... }(functionality));
Creating a local variable (instead of on window), and setting its content inside a self-invoked function (why?)
How do I declare a namespace in JavaScript?
var functionality = {
f1: function(){},
f2: function(){}
}
Pretty much the same as the previous thing but setting the contents without a self-invoking function (again why use or not use the self invoking function?).
So... which way is best?
I would suggest the module pattern for this, where a page is treated as a module. There is a lot of information about the javascript module pattern on the web. Have a look at http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html.
I've used an example from the link and modified it a bit:
var MyApp = MyApp || {};
MyApp.PageX = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
// ...
}
my.moduleProperty = 1;
my.moduleMethod = function () {
// ...
};
return my;
}());
What is happening here, is that a set of properties and methods is defined and namespaced to MyApp.PageX, MyApp being the global. So this will work:
MyApp.PageX.moduleProperty; // 1
MyApp.PageX.moduleMethod();
In the module pattern in JavaScript "Immediately-Invoked Function Expressions" (also known as self-executing anonymous functions) are used as self executing functions that return an object.
How can a self-executing function hide private variables and only expose the returned object. Why does this not happen with a normal JavaScript function?
So in the following mini module, why could we not achieve the same concept of encapsulation without the enclosing ()()?
var Module = (function () {
var privateVariable = "foo",
privateMethod = function () {
alert('private method');
};
return {
PublicMethod: function () {
alert(privateVariable);
privateMethod();
}
};
})();
How can a self-executing function hide private variables and only expose the returned object. Why does this not happen with a normal JavaScript function?
It does happen with normal JavaScript functions.
function MakeModule() {
var privateVariable = "foo",
privateMethod = function () {
alert('private method');
};
return {
PublicMethod: function () {
alert(privateVariable);
privateMethod();
}
};
}
var Module = MakeModule();
would work just fine.
The only difference is that the anonymous function introduces one less global variable and allows for itself to be garbage collected while MakeModule can't be collected unless explicitly deleted by the author.
The privateness is because of closures. The "var privateVariable" is closed over by "PublicMethod", so only that function can access the variable because only it has it in its closure. It cannot be referenced by anything else and is "private"
This happens not only in "Immediately-Invoked Function Expressions" but also in normal function calls. It is just a way to immediately create the closure when defining the module instead of doing it later when you call the outer function.
Also see this post from Douglas Crockford himself: http://javascript.crockford.com/private.html
You can define a anonymous function via named function.
Example:
//factorial
(function(n){
var self = function(n){
//call self
return n > 0 ? (self(n-1) * n) : 1;
}
return self;
})()
I see a lot of code like:
var myApp ={};
(function() {
console.log("Hello");
this.var1 = "mark"; //"this" is global, because it runs immediately on load. Caller is global
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
})();
Which causes the anonymous function to execute immediately. But what is the advantage of this, compared to just putting the code inline?
var myApp ={};
console.log("Hello");
var1 = "mark";
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
Apparently it's to do with scope of the function, but as the function is anonymous and called by window, it's scope (i.e. this) is global, no?
Usually, you would have this :
var myApp ={};
(function() {
console.log("Hello");
var var1 = "mark";
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
})();
The main difference is that var1 doesn't clutter the global namespace. After this call, var1 is still the same than before (generally undefined).
As var1 can only be accessed from the function defineds in the closure, it is said "private".
Apart avoiding possible causes of conflicts, it's just cleaner not to keep global variables when useless.
Here, you don't have a local variable but a global one defined as this.var1. It's probably a bug, or the reason would be found elsewhere in the code.
One reason: wrapping your code in an anonymous function allows you to create a module which distinguishes a public API from private functions and variables that are only used internally to the module. This avoids polluting the global namespace.
var myApp ={};
(function() {
console.log("Hello");
this.var1 = "mark";
function helper() {/*Some code here*/;}
myApp.sayGoodbye = function() {
helper()
console.log("Goodbye");
};
})();
I could say:
var myApp ={};
console.log("Hello");
var var1 = "mark";
function helper() {/*Some code here*/;}
myApp.sayGoodbye = function() {
helper()
console.log("Goodbye");
};
But then the global scope includes a function called helper which is of no use to anyone using your module, and could lead to possible naming conflicts with other modules.
I could alternatively just include helper as a method of myApp.
var myApp ={};
console.log("Hello");
var var1 = "mark";
myApp.helper = function() {/*Some code here*/;}
myApp.sayGoodbye = function() {
this.helper()
console.log("Goodbye");
};
However, I may wish to prevent users from directly calling helper, in which case this won't do.
I found some JavaScript syntax which is unknown for me and I even don't know how it's called or what it does so I can't find any documentation.
I found it on MDC Doc Center:
var Counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();
The part I am interested in is:
var Counter = (function() {})();
What the round brackets do? How this is called and where it can be used?
(function() {})() is an immediately executed function.
This creates private scope around a block of code. This also can create a closure which can be useful to maintain state after the function ends.
You require () around function() {} because function() {}() is an illegal statement (the JS parser fails).
Also it is a habit to make sure you wrap an immediately executed function in () so that readers of your code are aware they should be interested in the return value of the function instead of the function.
It's the module pattern. It's usually used to create singletons. See this answer:
What is this design pattern known as in JavaScript?
Consider when you have a function called a:
function a() {
alert("hi");
}
You call it like this:
a();
In (function() {})() you're just skipping the part where you defined the function before-hand. In one fell swoop, you've defined an unnamed function and called it.