Search code examples
javascriptnode.jsgulp

Can I bind the instance to non-static method immediately after creating instance of ES6-class?


Is it some way to assemble first two rows into one? I am not feeling comfortable to force users of MarkupPreprocessingHelper write two rows...

let markupPreprocessingHelper = new MarkupPreprocessingHelper(config);
let preprocessTemplates = markupPreprocessingHelper.takeCareAboutMarkupPreprocessing.bind(markupPreprocessingHelper);

gulp.task('Development run', gulp.series(
   preprocessTemplates,
   // ...
));

Solution

  • If you make a rebound copy of the function and save it as an instance property, you can then pass it around and users won't need to bind it manually:

    function someClass(name){
        this.name = name
        // make a prebound copy of myFunction
        this.preBound = this.myFunction.bind(this)
    }
    
    someClass.prototype.myFunction = function(){
        console.log(this.name)
    }
    
    let p = new someClass("Mark")
    
    // now you can pass a reference of it around without losing the binding
    let fn = p.preBound
    setTimeout(fn, 500)