Javascript function binding possible memory leak? - javascript

I wish I could think of a better question for my situation.
Let me give the context in code.
I have this general function intended for binding with different variations (only about 3 or 4 cases).
GeneralFunction = function(helper, paramA, paramB) {
if (paramA == "hello") {
return helper(paramA);
}
return paramB;
}
Then I have this function to return a particular variation of general function.
function getFlavorX() {
return GeneralFunction.bind(undefined, helperX);
}
My concern is that the getFlavorX() could be called many many times (thousands), and according to documentation of bind, seems each call to bind creates a new function. Even for the exact same helperX?
So I guess I am kind of leaking function objects?

I guess the concern is valid, but memory leak or not depends on rest of code. Since in my case, the variations of binding are very limited, I manually maintain the list of bindings function objects (I return an already binded function object, instead of let user codes invoke bind on each call).

Related

Add a method to a function that calls the function

Creating a module I ended designing a pattern where I attach methods to a function, and I'm not sure if it is correct. It is a closure that returns a function that has some methods attached which in turn calls the function itself.
I don't know if this is a bad practice or if it is considered to be ok. My objective is to provide ways to call the function with certain presents or in different ways, but I want to retain the ability to just call the function in its simpler form. Would this lead to memory leaks or anything like that?
I'm not making use of this at any point, so no danger of losing context.
Below you can find a code snippet with a simplified version.
function factory( general ){
var pusher = setTimeout(function(){ console.log('$',general) },1000);
var counter = 0;
function reporter ( specific ){
counter++;
console.log(counter, general , specific)
}
reporter.middleware = function ( something ){
clearTimeout(pusher);
return factory ( general + something )
}
return reporter
}
Thanks in advance.
Would this lead to memory leaks or anything like that?
No more than anything else. :-)
Since functions are proper objects in JavaScript, you can add properties to them, and those properties can refer to other functions. At a technical level, it's not a problem at all. For instance, jQuery does it with its $ function, which not only is callable ($()), but also has various other functions on it ($.ajax, $.Deferred, $.noConflict, etc.).
Whether it's good style or design is a matter, largely, of opinion, so a bit off-topic for SO. It may well be fine. Or it may be that you'd be better off returning a non-function object with your various functions on it as properties.

On Execution context of anonymous functions and call/apply/bind

I'm trying to get under the covers a little bit and get to understanding and not regurgitating code. I'm aware that bind, call and apply change the execution context by modifying what this points to. What I do not understand, is are arenas in which these methods are indispensable and/or lead to much shorter code. Consider the following:
var person = {
firstName: 'john',
lastName: 'doe',
fullName: function () {
console.log(this.firstName + " " + this.lastName);
}
}
//#1, binder is an html button
$('#binder').click(person.fullName.bind(person)); //john doe
//#2, anonymous is an html button
$('#anonymous').click(function () {
person.fullName(); //john doe
});
//seems strange I see this application a lot 'borrowing' a method
//why?
var o = { firstName: 'obj', lastName: 'ect' };
person.fullName.call(o); //obj ect to console
I would like to know some general paradigms about when it's good practice and/or a huge time saver to use call and apply (and bind outside of the not using anonymous functions a la function #1)
To focus on where each of these features are indispensable, I would say
apply is most useful when dealing with variadic functions. It lets you convert an array of values into an argument list.
function logwrapper(f){
return function(){
console.log("called");
return f.apply(this, arguments);
}
}
var bar = function(){ ... }
var foo = logwrapper(bar);
bind is most useful when you want to pass a method into some code that expects just a function. A common example is settimeout and other functions that expect callbacks:
setTimeout(function(){ obj.meth(); }, 100); //handwritten callback
setTimeout(obj.meth.bind(obj), 100); //Function.prototype.bind
setTimeout(bind(obj, "meth"), 100); //Some JS libraries have functions that
//let you write the object only once.
Just keep in mind that IE <=8 does not support the native Function.prototype.bind. You might need to use a polyfill or helper library in that case.
call is mostly useful for borrowing methods, as you already noticed. If this is going to be useful or not is going to depend a lot on your particular use case but an important use that is very common is using array methods on the arguments. For historical reasons, arguments doesn't have any of the usual array methods (slice, map, etc) so you need to borrow them:
function myvariadic(x){
var rest = [].slice.call(x, 1);
}
Another example you might see is the hasOwnProerty method:
for(k in obj){
if(Object.prototype.hasOwnProperty.call(obj, k)){
....
}
}
This lets you call the real hasOwnProperty method even if the object shadows it with a hasOwnProperty key of its own.
Frankly I don't give a twopenny toss about good or bad practices.
If your aim is to understand anything at all, you'd better forget about them.
This being said, to understand when it is appropriate to use call/apply or bind, what you have to understand is closures, and the specific closure of this.
I use a broad definition of closure here. Not the one you will usually get in JavaScript technical chats, where we usually talk about lexical closures.
For the purpose of this little post, let's say a closure will be anything that provides a value for any variable (this included) that lives outside the current scope of the function you're focusing on.
bind, call and apply are basically there to supply a value for this (and some other arguments as an option).
It is only useful for two things:
invoke functions or methods of a given class to an object of a different class (or no class at all).
more on that later
supply a value for this in case the current closure does not suit your needs.
For instance, passing a reference to a method loses the connection to the underlying object instance. Or using a class prototype function. Or being called in the context of an event handler where JS has set this to the DOM element that caught the event.
call & apply
call will simply set this to the value of its first argument for this particular execution of the function.
Since creating objects is so easy in JS, you might want to do something like:
Worker = function ()
{
this.things_done = 0;
}
Worker.prototype = {
do_something: function (count)
{
this.things_done += count;
}
}
var worker= new Worker(); // Worker object
var wanabee_worker = { things_done: 100 }; // classless object
Et voilà! You've just created something that has no class relation with Worker but still can use Worker methods, since it has all the required properties defined.
worker.do_something.call (wanabee_worker, 10);
allows wanabee_worker to borrow unrelated object Worker's methods.
The opposite can also be used:
function reset_work_count ()
{
this.things_done = 0;
}
reset_work_count.call (worker);
Here we have a plain function that does not have anything to do with Worker, except it uses the same properties. call allows to apply it to a Worker object.
apply does exactly the same as far as this is concerned. The only difference is the way other arguments are passed.
bind
bind will create an internal closure and return a new wrapper function that will use the parameter passed to bind as a value for this.
Typical example: bind an event handler to a specific object.
$('#binder').click(person.fullName.bind(person));
Beneath the JQuery goo, what the code does eventually is
binder.addEventListener ('click', person.fullName.bind(person), false);
If the handler was simply defined as person.fullName, it would be called with this set to the DOM element that caught the event.
In that particular case, the closure of this provided by the JS engine does not suit our needs, so we provide an alternative one using bind.
Instead of person.fullName.bind(person), you could have used:
function() { person.FullName(); }
except that
the lambda function is cumbersome and obfucates the code,
bind is an internal construct that does the closure a bit more efficiently.
You could also imagine that the object used to handle the event will be dynamically allocated/computed by some proxy function. In that case, using bind would be useless since what we want is access to the methods that will allow us to use a lambda object as one of a working class.
function event_handler (param)
{
var obj = compute_lambda_obj ();
Worker.prototype.do_something.call (ojb, param);
}

Is it better to exit from a Function to cut-down on Activation Objects, than recursively or calling nested functions?

In JavaScript and other languages, I've heard about Activation Objects being created as you invoke a method / function. In order to optimize and maintain a good performance, it sounds like a developer should limit how many functions are being called.
Now if there's no way around it and you must call multiple methods, is it better to call one method after another, like this:
myFunc1();
myFunc2();
myFunc3();
// or...
var myFuncs = [myFunc1, myFunc2, myFunc3];
for(var a=0, aLen=myFuncs.length; a<aLen; a++) {
myFuncs[a]();
}
OR, to nest them like this:
function myFunc1() {
// Do something...
myFunc2();
}
function myFunc2() {
// Do Something else...
myFunc3();
}
function myFunc3() {
//Do one last thing.
}
//Start the execution of all 3 methods:
myFunc1();
I'm assuming it makes more sense to go with the 1st technique, since it comes back to the previous scope and releases the last Activation Object... but if someone could confirm this,
I would really like to know!
Thanks
In order to optimize and maintain a good performance, it sounds like a developer should limit how many functions are being called.
Yes and no. Functions (or more generally, subroutines) are there to be called, and not doing so makes no sense. If you can make your code more DRY by introducing another function, do so.
The only place where not using them is reasonable are high-performance loops which run thousands of times doing little work, and function calls would add a noticable overhead. Do not try to prematurely optimize!
Also, there are some languages which handle recursion not well and where you will need to translate recursive function calls to loops, preventing stackoverflow exceptions. However, this is a rare case as well.
is it better to call one method after another, or to nest them?
That depends, since the two techniques do different things. With #1, there are just 3 independent functions which are called after each other. In contrast, #2 defines functions that always call each other - you can't get myFunc2 without myFunc3. Is that intended?
If it is, there's nothing wrong with this nesting. The two additional stack layers will not harm your performance.
For information concerning Activation Objects, please refer to http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/#more-546
This is not an optimization level concern however, as the concern you listed is an example of EXTREME pre-optimization and your time is not worth that type of investment. And actually, the example you listed above, there is little to no savings when you are looking at Activation Objects alone.
As for proper use however, I try to encapsulate as much as I can. If a function doesn't have to go in the global scope, and can live within the scope of another function, then that's where it should be declared.
for example, for better scoping.
var f2 = function() {
}
var f1 = function() {
f2()
}
// is not as nice as:
var f1 = function() {
var f2 = function()
f2()
}
// or even better..
var f1 = function() {
function() {
}() ; execute
}
Separation of responsibility:
private function myFunc1(): void
{
}
private function myFunc2(): void
{
}
private function myFunc3(): void
{
}
private function doAllFunc(): void
{
myFunc1();
myFunc2();
myFunc3();
}

closure or handler in object?

I click a button and there is a handler. I have never understood if I should use a closure, or let the handler be in a object. For example, in HTML I have,
<button id="b">Go</button>
<button id="c">Go</button>
and in JavaScript (with some jQuery),
var hdl=function(){
var hdl=function(){
foo+="foo"
console.log(foo)
},
foo=""
return hdl
}()
$("#b").click(hdl)
var obj={
bar:"",
hdl:function(){
this.bar+="bar"
console.log(this.bar)
}
}
var baz=function(){
obj.hdl()
}
$("#c").click(baz)
Both work. Or are there situations in which you can only use one of them?
An event handler is always a function or an object that implements the EventListener interface. I've never understood any reason to use an EventListener object rather than a function so I've only seen functions used, but you can use either.
If you choose a function, it's up to you whether you want a function to be a global function, an anonymously declared function or a function that is a property of an object. There is no "right" answer as it depends upon how you want to structure your code.
My event handlers are usually anonymously declared functions just because that's usually how I structure things and generally nothing more is needed. Simple is best so you should make it no more complicated than needed.
A closure is just a function body that survives longer than the simple execution of the function because some other function reference inside is still active. Whether to use a closure or not depends on your needs and again the structure of your code. Closures can be really handy ways of keeping some state without using global variables, but other times they aren't needed at all.
I think you're mixing up terms.
Closures are a natural result of JavaScript's scoping rules, not something you choose to create
The jQuery click event always takes a function. Whether that function is attached to an object—thereby making it a method—doesn't really matter. Depending on how that function is written, it may form a closure that affects you.
A closure is when a function "remembers" the variables in the context in which it's defined.
The classical closure example is something like this:
for(var i = 0; i < 10; i++)
$("#button" + i).click(function() { alert("you clicked button " + i); });
Most developers are surprised to learn that each button displays 10, which is the value of i when the outer scope ends. This happens because each of those functions declared in the loop has formed a closure over i. Those functions don't just get the value of i when they're declared, they get the actual i, in all its glory. That's why changing i after you create the function causes the created function to reflect the updated value of i
Situations like this are fixed by breaking the closure by passing i to a function, since function parameters are passed by value.
for(var i = 0; i < 10; i++)
(function(localI) {
$("#button" + i).click(function() { alert("you clicked button " + localI); });
)(i);
The only difference between your cases is that in one of them you are bundling your variables (foo) in an object. The following third example should make this point clear:
function hdl(variables){
variables.foo += variables.foo;
}
var obj = {foo: ""};
var baz = function(){
hdl(obj);
}
I don't think any of these alternatives is in anyway generally superior to the others. You should decide to use whatever solution is simpler and easier to understand and mantain depending on what your particular problem is.
For example, in the version using objects the variables are dinamically bound while in the version with closures they are statically bound. This means that the object version is more extensible (with inheritance, mixins, etc) while the closure version is more rigid (but simpler to reason about at compile time)

Question about Javascript model construction

I'm working on implementing a Javascript model on a web app that I'm working on. The purpose of the model is to simply hold information about the state of the page. I have come across two different implementations for creating the model and I was wondering which one was the best to use. The first implementation:
var PageInfo = function () {
this._info = {};
};
PageInfo.prototype = {
getInfo: function () {
return this._info;
},
setInfo: function (updatedInfo) {
this._info = updatedInfo;
}
};
The 2nd implementation:
var pageInfo = function () {
var info = {};
return {
getInfo: function () {
return info;
},
setInfo: function (updatedInfo) {
info = updatedInfo;
}
}
};
Another question I have is about the setInfo() function. When I find myself updating the model, I often want to have the info that I just changed immediately available to me. This has led me to write the setter function as such:
setInfo: function(updatedInfo) {
info = updatedInfo;
return info;
}
which I implement in the code like so:
var info = pageInfo.setInfo(newInfo);
Is this ok or should I be implementing it like this?:
pageInfo.setInfo(newInfo);
var info = pageInfo.getInfo();
Just trying to follow best practices and avoid any issues that may come up from using the wrong implementation.
Both implementations are perfectly acceptable. The former will be faster, albeit by a negligible amount, but exposes its internals to the world. This means that any variable that holds a reference to an instance of PageInfo will be able to manipulate the _info property. Generally this is a non-issue as properties that being with an underscore (_) are considered to be private and should be left alone.
The latter implementation makes use of a concept called closure. A closure is formed when a value is returned that maintains a reference to its defining scope. Essentially it means that the info variable is kept alive. Since the variable is "closed over" it's impossible for it to be modified outside of the interface methods that you provide. In my experience this is rarely needed.
In regards to your second question, again either is acceptable. I like the interface for accessor methods to be consistent so I would say that setInfo should not return anything but there are exceptions to every rule. The exception to the rule occurs when the the value returned by getInfo will not be congruent with what was passed to setInfo. That is, if getInfo returns different value than the value passed to setInfo you might want to return the value out of setValue. Otherwise, the caller could simply re-use the value that was passed to setValue instead of calling getValue.
1st implementation is better, as in 2nd implementation every time you call pageInfo function, you are defining 2 new functions (or set up a closure), while 1st implementation is defining them in prototype and reusing.
For other question, if you only do this to preserve lines, i might suggest something like:
var info = pageInfo.setInfo(newInfo) || pageInfo.getInfo();
assuming setInfo returns undefined.

Categories

Resources