创建ES6-class实例后,是否可以立即将实例绑定到非静态方法?

时间:2018-12-13 01:16:13

标签: javascript node.js gulp

以某种方式将前两行组装成一个吗?我不愿意强迫MarkupPreprocessingHelper的用户写两行...

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

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

1 个答案:

答案 0 :(得分:1)

如果您复制该函数的副本并将其另存为实例属性,则可以将其传递给用户,而用户则无需手动绑定它:

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)