A
A
Arks2014-12-11 01:37:29
JavaScript
Arks, 2014-12-11 01:37:29

How to get rid of bind in javascript libs?

Increasingly, they notice that inside functions I write code like

...
var a = _.bind(function(options){
...
this.somePropertyToChange = options.doSomething();
this.doSomething();
...
}, this)
...

Such lines are becoming a replacement for simple static-binding at the var self = this level more and more often as chains deepen. But is it right? Can promises or even just events/observer help? Is it really necessary to do everything in javascript on events in order to feel comfortable and ensure code reuse? When to write linear code and when to decompose? How to ensure the correct dispose of events?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2014-12-11
@Arks

Can promises or even just events/observer help?

What? What does this have to do with it?
Again, what? Read... I don't know... about lambda calculus, functional programming... What do events have to do with it? In your example, we are explicitly setting the function context through currying:
_.bind = function (fn, context) {
    
    return function () {
        return fn.apply(context, arguments);
    };    
};

This allows us to get rid of the outer scope inside the function and be sure that the function has the correct context. Suddenly, you decide to change your self = this to self = undefined later, or change self to that... you never know... Less connection - more happiness.
Linear where linear code is needed, and an event model when interacting with I / O, since it must be asynchronous. In general, all these muddles with callbacks and the principles by which the "decomposition" takes place take into account such a thing as an event-loop. In any case, this does not apply to the subject of the question from the title.
Understand how javascript works and you will be happy.
ps And what do you write on that ask such questions? Satisfy my curiosity.

S
Sergey Melnikov, 2014-12-11
@mlnkv

Read something sensible on js and maybe then you will have an understanding.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question