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

房东的猫 提交于 2019-12-12 01:19:28

问题


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)


来源:https://stackoverflow.com/questions/53753691/can-i-bind-the-instance-to-non-static-method-immediately-after-creating-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!