T
T
Topsky2017-04-12 19:25:09
JavaScript
Topsky, 2017-04-12 19:25:09

Javascript how to add function to function?

Good afternoon ladies and gentlemen.
I started writing a module for myself, for operating with a json file, my head does not understand how to implement the save function with blackjack and courtesans.

module.exports = function(filename, callback){
     callback(filename)
}

module.exports.save = function(filename){
    ...fs...save()
}

I want to achieve this result, but I don’t understand how to make a function that will have a function.
Mdl('file.json', function(data){
  data['blablabla'] = 12345;
}).save();

i.e. fs has pipe(), on(), and so on, so I want to understand how to implement it, I saw the original function on
a series of manipulations, and at the end you can call save('file')
Example.
ffmpeg('/path/to/file.avi')
  .videoCodec('libx264')
  .audioCodec('libmp3lame')
  .size('320x240')
  .on('error', function(err) {
    console.log('An error occurred: ' + err.message);
  })
  .on('end', function() {
    console.log('Processing finished !');
  })
  .save('/path/to/output.mp4');

Here is how this sequence of functions is implemented?
--UPDATE, so I figured it out a bit
But the question is, how is .save() implemented?
if in the callback of the main function, I write the local date
Mdl('file.json', function(data){
  data['blablabla'] = 12345;
}).save();

Then how to pass it to save without an argument?
In ffmpeg, only the path + file name is specified,
the implementation of save () is something like this
module.exports = function(filename, callback){
  this.data = callback(require(filename));
    return { 
        save: function() {
      //console.log(callback);
      fs.writeFile(filename, data);
        }
    };
}

I can't figure out what's what...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yustas Alexu, 2017-04-12
@Topsky

To do this, you just need to return an object from each function in the chain, in which there will be methods like save. The most simplified example:

function foo() {
    return { 
        save: function() {
            return true;
        }
    };
}

foo().save(); // true

In the case of OOP, this chain would return an instance of a class (instance of class). And in a class instance, you can already call methods of this class itself.
class Foo {
    constructor() {}
    someMethod() {
        return this;
    }
    anotherMethod() {
        return this;
    }
    save() {
        return this;
    }
}

var obj = new Foo();
obj.someMethod().anotherMethod().save().someMethod().anotherMethod().save();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question