Can I bind the instance to non-static method immed

2019-08-30 00:54发布

问题:

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,
   // ...
));

回答1:

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)